How to get height of a Widget in Flutter?

CodeWithFlutter
2 Min Read

To get the height of a widget in Flutter, you can use the key property and the GlobalKey class. A GlobalKey is a unique identifier for a widget, and it can be used to find the size and position of the widget in the tree.

Here’s an example of how to get the height of a Container widget:

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  GlobalKey _containerKey = GlobalKey();

  @override
  Widget build(BuildContext context) {
    return Container(
      key: _containerKey,
      height: 100,
      width: 100,
      color: Colors.blue,
    );
  }

  void getHeight() {
    final RenderBox renderBox = _containerKey.currentContext.findRenderObject();
    final height = renderBox.size.height;
    print("Height: $height");
  }
}

In this example, we assign a GlobalKey to the Container widget. After the widget has been rendered, we can use the findRenderObject method of the BuildContext object to get the RenderBox object for the widget. Then, we can access the size property of the RenderBox object to get the height of the widget.

Note that this method only works when the widget has been fully rendered, so it’s important to call the getHeight method after the widget has been built, for example, in a StatefulWidget‘s didUpdateWidget method or using the Future.delayed method.

Share this Article
Leave a comment