flutter 總結: 通過 GlobalKey 獲取介面任意元素座標尺寸

SoaringHeart發表於2021-07-29

最初:

需求開發中遇到要獲取螢幕任意元素座標尺寸的功能,最終實現如下:

1. example:

//...
GlobalKey _globalKey = GlobalKey();

@override
Widget build(BuildContext context) {
    //...
    ElevatedButton.icon(
      icon: Icon(Icons.send),
      label: Text("傳送"),
      // onPressed: () => ddlog('pressed'),
      key: _globalKey,
      onPressed: (){
        // _showCustomPopView();
        ddlog(_globalKey.globalOffset());// Offset(143.5, 117.0)
        ddlog(_globalKey.globalSize());// Size(88.0, 48.0)
      },
    ),
    //...
}

複製程式碼

2. extension 封裝:

import 'package:flutter/material.dart';

extension GlobalKeyExt on GlobalKey{

  /// 獲取當前元件的 Offset
  Offset globalOffset() {
    if (this.currentContext == null) {
      return Offset.zero;
    }

    RenderObject? renderObj = this.currentContext!.findRenderObject();
    if (renderObj == null || renderObj is! RenderBox) {
      return Offset.zero;
    }
    RenderBox renderBox = renderObj;
    var point = renderBox.localToGlobal(Offset.zero); //元件座標
    return point;
  }

  /// 獲取當前元件的 Size
  Size globalSize() {
    if (this.currentContext == null) {
      return Size.zero;
    }
    RenderObject? renderObj = this.currentContext!.findRenderObject();
    if (renderObj == null || renderObj is! RenderBox) {
      return Size.zero;
    }
    RenderBox renderBox = renderObj;
    return renderBox.size;
  }
}
複製程式碼

相關文章