当前位置:   article > 正文

【Flutter】二十八、Flutter中获取widget尺寸及位置信息

【Flutter】二十八、Flutter中获取widget尺寸及位置信息

一、获取屏幕宽高

1.1 MediaQuery

  • 获取屏幕尺寸。单位dp
MediaQuery.of(context).size // Size(414.0, 896.0)
  • 1
  • 获取设备像素密度
MediaQuery.of(context).devicePixelRatio; // 2.0
  • 1

1.2 window

使用window需要引入dart:ui库。

  • 获取屏幕尺寸。单位px(px = dp * 像素密度)
window.physicalSize; // Size(828.0, 1792.0)
  • 1
  • 获取设备像素密度
window.devicePixelRatio; // 2.0
  • 1

二、获取widget尺寸及位置

    使用widget中的key可以获取widget的尺寸及位置信息。

class GetWidgetSize extends StatelessWidget {
  GlobalKey _key1 = GlobalKey();
  GlobalKey _key2 = GlobalKey();
  GlobalKey _key3 = GlobalKey();

  @override
  Widget build(BuildContext context) {
  	// 监听widget渲染完成
	WidgetsBinding.instance.addPostFrameCallback((duration){
      RenderBox box = _key1.currentContext.findRenderObject();
      // _key1.currentContext.size; Size(200.0, 100.0)
      print(box.size); // Size(200.0, 100.0)
      print(box.localToGlobal(Offset.zero)); // Offset(107.0, 100.0)
    });

    // TODO: implement build
    return Center(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Container(
            key: _key1,
            constraints: BoxConstraints.tight(Size(200, 100)),
            color: Colors.red,
          ),
          Container(
            key: _key2,
            margin: EdgeInsets.symmetric(vertical: 30.0),
            constraints: BoxConstraints.tight(Size(200, 100)),
            color: Colors.yellow,
          ),
          Container(
            key: _key3,
            constraints: BoxConstraints.tight(Size(200, 100)),
            color: Colors.blue,
          ),
        ],
      ),
    );
  }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/268756
推荐阅读
相关标签
  

闽ICP备14008679号