Flutter, How to get the size of a widget?

In the link you referred to, after creating the GlobalKey it is assigned to the red container

but in your code you haven't assigned it to the container so it can be referred to from the _getSizes() and _getPositions(), _keyRed have to be attached to a Context in your code before you use it.

//creating Key for red panel
GlobalKey _keyRed = GlobalKey();
    ...
    //set key
        Flexible(
                 flex: 2,
                 child: Container(
                   key: _keyRed, // assigned as a key of the red container.
                   color: Colors.red,
                 ),
         ),

You can wrap in LayoutBuilder:

return LayoutBuilder(
    builder: (BuildContext context, BoxConstraints constraints) {
//      height: constraints.maxHeight,
//      width: constraints.maxWidth
        return YourWidget();
    }
);

There is no direct way to calculate the size of the widget, so to find that we have to take the help of the context of the widget.

Calling context.size returns us the Size object, which contains the height and width of the widget. context.size calculates the render box of a widget and returns the size.

Checkout https://medium.com/flutterworld/flutter-how-to-get-the-height-of-the-widget-be4892abb1a2


This is because the _keyRed is not attached to Context in your code.

to fix it -

 @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _keyRed,  //Add this.
      appBar: AppBar(