在項(xiàng)目中需要在控件渲染之后獲取控件的坐標(biāo)位置
...
/// 控件的key
GlobalKey _anchorKey = GlobalKey();
/// 控件中心坐標(biāo)
double dx, dy;
void initState() {
super.initState();
// 在控件渲染完成后執(zhí)行的回調(diào)
WidgetsBinding.instance.addPostFrameCallback((_) {
_findRenderObject();
});
}
// 如果控件用了Transform平移旋轉(zhuǎn)等, 獲取到的坐標(biāo)也會變化
_findRenderObject() {
RenderBox renderBox = _anchorKey.currentContext.findRenderObject();
// offset.dx , offset.dy 就是控件的左上角坐標(biāo)
var offset = renderBox.localToGlobal(Offset.zero);
setState(() {
dx = offset.dx + (renderBox.size.width / 2);
dy = offset.dy + (renderBox.size.height / 2);
});
}
Widget widgetContainer() {
return Container(
// key 要綁定在該控件上
key: _anchorKey,
width: 100,
height: 100);
}
...
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者