dart - 如何在 Flutter 的屏幕上获取小部件的绝对坐标?
问题描述
如何在 Flutter 的屏幕上获取小部件的绝对坐标?
或者它在父级中的偏移量
例子:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Simple app',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: SimpleScreen(
title: 'Simple screen',
),
);
}
}
class SimpleScreen extends StatefulWidget {
final String title;
SimpleScreen({Key key, this.title}) : super(key: key);
@override
_SimpleScreenState createState() => new _SimpleScreenState();
}
class _SimpleScreenState extends State<SimpleScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Container(
width: 48.0,
height: 48.0,
color: Colors.blue,
),
),
);
}
}
目标是获取容器在父级中的偏移量。如果 Center 的大小为 48.0,则容器在 Center 的 parent/root 中的偏移量
条件:你不知道包装布局(它是一个库小部件),应该是灵活的,没有硬编码的值
谢谢
解决方案
你可以使用我写的这个扩展(需要 Dart 2.6):
extension GlobalKeyExtension on GlobalKey {
Rect? get globalPaintBounds {
final renderObject = currentContext?.findRenderObject();
final translation = renderObject?.getTransformTo(null).getTranslation();
if (translation != null && renderObject?.paintBounds != null) {
final offset = Offset(translation.x, translation.y);
return renderObject!.paintBounds.shift(offset);
} else {
return null;
}
}
}
示例如何使用它:
final containerKey = GlobalKey();
Container(
key: containerKey,
width: 100,
height: 50,
)
void printWidgetPosition() {
print('absolute coordinates on screen: ${containerKey.globalPaintBounds}');
}
推荐阅读
- c - 在c中使用管道在父子之间发送数据
- java - Android:启动画面模糊且有圆角
- android - 重叠碰撞区域无法触发触摸事件
- python - python站点请求,布尔类上的打印错误
- virtualization - 虚拟机管理器 (VMM) 和管理程序是否指代同一事物?
- html - 如何使悬停触发CSS中的另一个悬停?
- angular - 访问 gmail api 时没有“Access-Control-Allow-Origin”
- html - 尽管给出了正确的图像路径,但没有显示背景图像
- javascript - 内部文字不会改变
- mongodb - 您可以将 $sample 管道与 Parse Server 一起使用吗?