如何在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,
),
),
);
}
}
目标是在父母中获得Container的抵消。如果中心的大小是48.0,那么Container在中心的父/根
中的偏移量条件:你不知道包装器布局(它是一个库小部件),应该是灵活的,没有硬编码的值
谢谢
答案 0 :(得分:0)
答案 1 :(得分:0)
您可以使用我编写的扩展名(需要Dart 2.6):
extension GlobalKeyEx on GlobalKey {
Rect get globalPaintBounds {
final renderObject = currentContext?.findRenderObject();
var translation = renderObject?.getTransformTo(null)?.getTranslation();
if (translation != null && renderObject.paintBounds != null) {
return renderObject.paintBounds
.shift(Offset(translation.x, translation.y));
} else {
return null;
}
}
}
final containerKey = GlobalKey();
Rect get containerRect => containerKey.globalPaintBounds;
Container(
key: containerKey,
width: 100,
height: 50,
)
void printContainerWidgetGlobalRect() {
print('rect: ${containerRect}');
}