Flutter: How to get the height of the widget?
Sometimes we required to calculate the height of widgets by any reason to render the belonging widgets on the screen. So, let's dive deep inside to know how flutter calculates the size.

So before jumping towards code, We would understand How widgets are rendered on screen? for that we have to first look at RenderObject.
RenderObject: Rendering of the widget is done by RenderObject, It handles the size, layout, and painting of the widget when Flutter Engine draws UI. Each widget has the rendered object which holds the configuration of widgets that are drawn on the screen.
So with the above explanation, you may already have an idea, about how we can get the height of the widget.
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.
Calling this getter is theoretically relatively expensive (O(N) in the depth of the tree), but in practice is usually cheap because the tree usually has many render objects and therefore the distance to the nearest render object is usually short.
Example:
class WidgetSize extends StatefulWidget {
final Widget child;
final Function onChange;
const WidgetSize({
Key key,
@required this.onChange,
@required this.child,
}) : super(key: key);
@override
_WidgetSizeState createState() => _WidgetSizeState();
}
class _WidgetSizeState extends State<WidgetSize> {
@override
Widget build(BuildContext context) {
SchedulerBinding.instance.addPostFrameCallback(postFrameCallback);
return Container(
key: widgetKey,
child: widget.child,
);
}
var widgetKey = GlobalKey();
var oldSize;
void postFrameCallback(_) {
var context = widgetKey.currentContext;
if (context == null) return;
var newSize = context.size;
if (oldSize == newSize) return;
oldSize = newSize;
widget.onChange(newSize);
}
}
Use above Widget Like:
WidgetSize widget returns the onChange callback which includes the size of the child widget.
Size textSize;
WidgetSize(
onChange: (Size size) {
setState(() {
textSize = size;
});
},
child: Text(
"Size - $textSize",
textAlign: TextAlign.center,
),
),
Output:
