Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

dart - How to get widget's absolute coordinates on a screen in Flutter?

How to get widget's absolute coordinates on a screen in Flutter?

Or its offset in a parent

Example:

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

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

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
    }
  }
}

Example how to use it:

final containerKey = GlobalKey();

Container(
  key: containerKey,
  width: 100,
  height: 50,
)

void printWidgetPosition() {
  print('absolute coordinates on screen: ${containerKey.globalPaintBounds}');
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...