Stackademic

Stackademic is a learning hub for programmers, devs, coders, and engineers. Our goal is to…

Follow publication

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:

--

--

Published in Stackademic

Stackademic is a learning hub for programmers, devs, coders, and engineers. Our goal is to democratize free coding education for the world.

Written by Mohit Gupta

Flutter Developer | Wheelseye Technology

Responses (1)