使用 WidgetsBindingObserver获取
class CloseTap extends StatefulWidget {
@override
_CloseTapTapState createState() => _CloseTapTapState();
} class _CloseTapTapState extends State<CloseTap> with WidgetsBindingObserver {
void _onAfterRendering(Duration timeStamp) {
RenderObject renderObject = context.findRenderObject();
//获取元素大小
Size size = renderObject.paintBounds.size;
//获取元素位置
var vector3 = renderObject.getTransformTo(null)?.getTranslation();
CommonUtils.showChooseDialog(context, size, vector3);
} @override
Widget build(BuildContext context) {
return GestureDetector(
child: Icon(Icons.close),
onTapDown: (TapDownDetails details) {
WidgetsBinding.instance.addPostFrameCallback(_onAfterRendering);
setState(() {
});
},
);
}
目的是为了实现如图
在点击X号的时候按照X号的位置进行位置计算
小三角是使用了Clip功能
Positioned(
left: dx - 10.0,
top: dy < h / 2 ? dy - wx / 2 : null,
bottom: dy < h / 2 ? null : (h - dy - wx / 2),
child: ClipPath(
clipper: Triangle(dir: dy - h / 2),
child: Container(
width: 30.0,
height: 30.0,
color: Colors.white,
child: null,
),
),
),
class Triangle extends CustomClipper<Path> {
double dir;
Triangle({this.dir});
@override
Path getClip(Size size) {
var path = Path();
double w = size.width;
double h = size.height;
if (dir < 0) {
path.moveTo(0, h);
path.quadraticBezierTo(0, 0, w * 2 / 3, 0);
path.quadraticBezierTo(w / 4, h / 2, w, h);
} else {
path.quadraticBezierTo(0, h / 2, w * 2 / 3, h);
path.quadraticBezierTo(w / 3, h / 3, w, 0);
path.lineTo(0, 0);
}
return path;
} @override
bool shouldReclip(CustomClipper<Path> oldClipper) => false;
}
代码部分见github项目 https://github.com/dnoyeb/syk_flutter