Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the offset of a Widget

Tags:

flutter

dart

I want to get the offset of a StatefulWidget, as I need it to set the positioning of an OverlayEntry widget. I have tried to get the offset using the following snippets:

    final renderBox = context.findRenderObject();
    final offset = renderBox.localToGlobal(Offset.zero);
   final _key = GlobalKey();
   /* ----------Some code------------- */
   final renderBox = _key.currentContext.findRenderObject();
   final offset = renderBox.localToGlobal(Offset.zero);

But each time I do either of these, I get this error message from the Dart Analyzer:

The method 'localToGlobal' isn't defined for the type 'RenderObject'.
Try correcting the name to the name of an existing method, or defining a method named 'localToGlobal'.

This is the version of Flutter that I am currently using:

[√] Flutter (Channel stable, v1.17.5, on Microsoft Windows [Version 10.0.18363.900], locale en-NG)
Flutter 1.17.5 • channel stable • https://github.com/flutter/flutter.git
Framework • revision 8af6b2f038 (8 days ago) • 2020-06-30 12:53:55 -0700
Engine • revision ee76268252
Tools • Dart 2.8.4
like image 233
Developal Avatar asked Sep 05 '25 16:09

Developal


1 Answers

Hi i faced the same issue. Like how they disscussed here, you should specify the variable type. So you have to do like this:

final _key = GlobalKey();
/* ----------Some code------------- */
final RenderBox renderBox = _key.currentContext.findRenderObject();
final offset = renderBox.localToGlobal(Offset.zero);
like image 186
Gioele Avatar answered Sep 07 '25 09:09

Gioele