Member-only story
How to get the height and width of widget in Flutter
Hello everyone, there are many cases where we need to determine the size of a particular widget, such as its height and width. Today, we’ll explore a specific method to achieve this.
In Flutter, a RenderObject is a low-level class responsible for the layout, painting, and hit-testing of widgets on the screen. High-level widgets like Container, Row, and Column rely on underlying RenderObject classes to manage their rendering on the screen.
Step 1: Declare the global key and Size variable
final GlobalKey _globalKey = GlobalKey();
Size _size = const Size(0, 0);
Step 2: Declare the function which return the size of widget.
Size getSizeOfWidget() {
RenderBox? renderBox = _globalKey.currentContext?.findRenderObject() as RenderBox?;
if (renderBox != null) {
return renderBox.size;
}
return const Size(0, 0);
}
Step 3: Get the size of widget in initState()
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
_size = getSizeOfWidget();
setState(() {});
});
}
Output: