【问题标题】:How to get widget's absolute coordinates on a screen in Flutter?如何在 Flutter 的屏幕上获取小部件的绝对坐标?
【发布时间】:2018-10-23 06:45:25
【问题描述】:

如何在 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,那么Container在Center的parent/root中的偏移量

条件:你不知道包装布局(它是一个库小部件),应该是灵活的,没有硬编码的值

谢谢

【问题讨论】:

标签: dart flutter


【解决方案1】:

你可以使用我写的这个扩展(需要 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}');
}

【讨论】:

  • 如何在函数内调用Rect get containerRect =&gt; containerKey.globalPaintBounds;。我需要定期获取动画容器的位置,所以我想在 Timer.Periodic 中调用它?
  • @TusharGautam 只需将我的答案中的扩展名保存到 dart 文件中,然后将此文件导入到您尝试使用的任何地方containerKey.globalPaintBounds。
【解决方案2】:

也许这个简单的小部件就是你想要的: rect_getter 0.0.1

这是一个小部件,提供了一种在渲染后获取子矩形信息的简单方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-01
    • 1970-01-01
    • 2020-04-13
    • 2020-09-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多