2018-12-21 获取widget的宽高

//标识widget的key
GlobalKey _keyRed = GlobalKey();

Container(
 key: _myKey,
 child: Text('hello'),
)
//高度
_getSize() {
  final RenderBox renderBox = _myKey.currentContext.findRenderObject();
  final size = renderBox.size;
  print('size: $size');
}
//坐标
_getPositions() {
  final RenderBox renderBox = _myKey.currentContext.findRenderObject();
  final position = renderBox.localToGlobal(Offset.zero);
  print('positon: $position');
}

//上面两个方法要在widget渲染之后调用
void initState() {
  WidgetsBinding.instance.addPostFrameCallback(_layoutCallback);
  super.initState();
}
_layoutCallback(_) {
  _getSize();
  _getPositions();
}

你可能感兴趣的:(2018-12-21 获取widget的宽高)