最初:
需求开发中遇到要获取屏幕任意元素坐标尺寸的功能,最终实现如下:
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.position());// Offset(143.5, 117.0)
ddlog(_globalKey.size);// Size(88.0, 48.0)
},
),
//...
}
2. extension 封装:
import 'package:flutter/material.dart';
extension BuildContextExt on BuildContext {
/// 获取当前组件的 RenderBox
RenderBox? renderBox() {
return this.findRenderObject() is RenderBox ? (this.findRenderObject() as RenderBox) : null;
}
/// 获取当前组件的 position
Offset? position({Offset offset = Offset.zero}) {
return this.renderBox()?.localToGlobal(offset);
}
}
extension GlobalKeyExt on GlobalKey{
/// 获取当前组件的 RenderBox
RenderBox? renderBox() => this.currentContext?.renderBox();
/// 获取当前组件的 position
Offset? position({Offset offset = Offset.zero}) => this.currentContext?.position(offset: offset);
/// 获取当前组件的 Size
Size? get size => this.currentContext?.size;
}