Outline
Sometimes, when developing an app in Flutter
, you need to get the size of a widget. In this blog post, I will introduce how to use LayoutBuilder
to get the size of a widget.
- Official document: LayoutBuilder
You can see the full source code of this blog post in the link below.
LayoutBuilder
By using LayoutBuilder
, you can get the width and height of a specific widget.
Widget size
To get the size of a specific widget, use the LayoutBuilder
widget as the parent or child widget of the widget.
...
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: LayoutBuilder(builder: (
BuildContext context,
BoxConstraints constraints,
) {
print('FloatingActionButton minWidth: ${constraints.minWidth}');
print('FloatingActionButton maxWidth: ${constraints.maxWidth}');
print('FloatingActionButton minHeight: ${constraints.minHeight}');
print('FloatingActionButton maxHeight: ${constraints.maxHeight}');
return const Icon(Icons.add);
}),
),
...
When you run this code, you can see the size of the widget as follows.
flutter: FloatingActionButton minWidth: 0.0
flutter: FloatingActionButton maxWidth: 56.0
flutter: FloatingActionButton minHeight: 0.0
flutter: FloatingActionButton maxHeight: 56.0
body size
You can get the size of body
in the same way. The code to get the size of body
using LayoutBuilder
is as follows.
...
body: LayoutBuilder(
builder: (
BuildContext context,
BoxConstraints constraints,
) {
print('body minWidth: ${constraints.minWidth}');
print('body maxWidth: ${constraints.maxWidth}');
print('body minHeight: ${constraints.minHeight}');
print('body maxHeight: ${constraints.maxHeight}');
return Center(
...
);
},
),
...
When you run this code, you can see the size of body
as follows.
flutter: body minWidth: 0.0
flutter: body maxWidth: 393.0
flutter: body minHeight: 0.0
flutter: body maxHeight: 737.0
Completed
Done! We’ve seen how to use LayoutBuilder
to get the size of a specific widget. If you need to get the size of a specific widget, please refer to this blog and try using LayoutBuilder
.
Was my blog helpful? Please leave a comment at the bottom. it will be a great help to me!
App promotion
Deku
.Deku
created the applications with Flutter.If you have interested, please try to download them for free.