Flutter: Finding X and Y coordinates of a widget at runtime

Last updated on January 8, 2021 A Goodman Loading... Post a comment

There may be times you want to calculate the X and Y positions of a widget in your Flutter application, for instance, programmatically scrolling to a particular destination when the user presses a tab or a button, etc.

  • X: The left position (in pixels) relative to the left of the screen.
  • Y offset: The top position (in pixels) relative to the top of the screen.

To get the exact position of a widget, we need to give it a key. To make it easier to understand, see the following example.

Example

This example contains an orange box and a floating button. Once the user presses the button, we’ll calculate then display the X and Y coordinates of the box on the screen.

Preview:

The full code:

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Kindacode.com',
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  GlobalKey _key = GlobalKey();
  double _x, _y;

  // this function is trigger when the user presses the floating button
  void _getOffset(GlobalKey key) {
    RenderBox box = key.currentContext.findRenderObject();
    Offset position = box.localToGlobal(Offset.zero);
    setState(() {
      _x = position.dx;
      _y = position.dy;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Kindacode.com'),
      ),
      body: Center(
        child: Stack(children: [
          Positioned(
            top: 100,
            left: 30,
            child: Container(
              key: _key,
              width: 360,
              height: 200,
              padding: EdgeInsets.all(30),
              color: Colors.amber,
              child: Text(
                _x != null ? "X: $_x, \nY: $_y" : 'Press the button to calculate',
                style: TextStyle(fontSize: 24),
              ),
            ),
          ),
        ]),
      ),
      floatingActionButton: FloatingActionButton(
          onPressed: () => _getOffset(_key),
          child: Icon(Icons.calculate)),
    );
  }
}

If you would like to learn more about Flutter, read also the following articles: Flutter: Scrolling to a desired Item in a ListViewFlutter SliverListUsing Stack and IndexedStack in FlutterProgrammatically show/hide a widget using Visibility, or check out our Flutter topic page and Dart topic page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles