如何在Flutter的屏幕上获取小部件的绝对坐标?

时间:2018-05-13 12:40:25

标签: 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,
        ),
      ),
    );
  }
}

目标是在父母中获得Container的抵消。如果中心的大小是48.0,那么Container在中心的父/根

中的偏移量

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

谢谢

2 个答案:

答案 0 :(得分:0)

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

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

demo

答案 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}');
}