Flutter 小知識,Key的使用(獲取當前點選Widget位置/獲取當前Widget大小)

多少艾克可以重來 發表於 2020-12-04

初始化key:

  GlobalKey _keyGreen = GlobalKey();

引用Key:

  InkWell(
            child: Container(
              margin: EdgeInsets.only(left: 30),
              child: Text(
                "Key測試",
                textAlign: TextAlign.center,
              ),
            ),
            key: _keyGreen,
            onTap: () {
              //獲取當前Widget大小
              final RenderBox renderBox =
                  _keyGreen.currentContext.findRenderObject();
              final sizeGreen = renderBox.size;
              print("SIZEofgreen: $sizeGreen");

              //獲取當前螢幕位置
              final positionGreen = renderBox.localToGlobal(Offset.zero);
              print("POSITIONofgreen: $positionGreen");
            },
          )

獲取螢幕位置:

final RenderBox renderBox = _keyGreen.currentContext.findRenderObject();
              final positionGreen = renderBox.localToGlobal(Offset.zero);
              print("POSITIONofgreen: $positionGreen");

獲取當前Widget大小:

final RenderBox renderBox = _keyGreen.currentContext.findRenderObject();
 final sizeGreen = renderBox.size;
print("SIZEofgreen: $sizeGreen");

注意:
一定要標識key

在這裡插入圖片描述