如何在Flutter中在屏幕上获取小部件的绝对坐标? [英] How to get widget's absolute coordinates on a screen in Flutter?
本文介绍了如何在Flutter中在屏幕上获取小部件的绝对坐标?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在Flutter中获取小部件在屏幕上的绝对坐标?
How to get widget's absolute coordinates on a screen in 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在父级中的偏移量。如果Center的大小为48.0,则Container在Center的父级/根目录中的偏移量
Goal is to get Container's offset in parent. If Center's size is 48.0, then Container's offset in Center's parent/root
条件:您不知道包装器的布局(它是一个库小部件),应该灵活一些,没有硬编码的值
Condition: you don't know the wrapper layout (it's a library widget), should be flexible, without hardcoded values
谢谢
推荐答案
您可以使用此扩展名I写道(需要Dart 2.6):
You can use this extension I wrote (requires Dart 2.6):
extension GlobalKeyExtension 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 printWidgetPosition() {
print('absolute coordinates on screen: ${containerRect}');
}
这篇关于如何在Flutter中在屏幕上获取小部件的绝对坐标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文