Flutter — How to get height of a Widget?
A short tutorial for getting height of an widget in Flutter.
To get the size/position of a widget on screen, you can use GlobalKey
to get its BuildContext
to then find the RenderBox
of that specific widget, which will contain its global position and rendered size.
Just one thing to be careful of: That context may not exist if the widget is not rendered. Which can cause a problem with ListView
as widgets are rendered only if they are potentially visible.
Another problem is that you can’t get a widget’s RenderBox
during build
call as the widget hasn't been rendered yet.
But I need to the size during the build! What can I do?
There’s one cool widget that can help: Overlay
and its OverlayEntry
. They are used to display widgets on top of everything else (similar to stack).
But the coolest thing is that they are on a different build
flow; they are built after regular widgets.
That have one super cool implication: OverlayEntry
can have a size that depends on widgets of the actual widget tree.
Okay. But don’t OverlayEntry requires to be rebuilt manually?
Yes, they do. But there’s another thing to be aware of: ScrollController
, passed to a…