LayoutBuilder
Learning objectives
- You know how to use the LayoutBuilder widget.
The LayoutBuilder widget has access to the size of the parent widget, which can be used to make decisions on what to show. The following example outlines the use of LayoutBuilder, deciding on which layout widget to use based on the screen size.
The constructor of LayoutBuilder
has an attribute builder
, which takes a function as a parameter. The function is given a BuildContext
and an instance of BoxConstraints. The BoxConstraints
has properties which can be used to determine the size of the parent widget; in the example above, we use the maxWidth
property to decide the widget based on the parent width. If the width of the parent is smaller than 640
pixels, we show the PhoneLayout
. Otherwise, we show the DesktopLayout
.
In a similar vein, for mobile devices, we could have all the contents of the application in a single column, while for other devices, the layout could be different. As an example, we could define three high-level widgets, one for showing a menu, one for showing news items, and one for showing advertisements.
class MenuWidget extends StatelessWidget {
Widget build(BuildContext context) {
return Expanded(child: Container(color: Colors.blue));
}
}
class NewsWidget extends StatelessWidget {
Widget build(BuildContext context) {
return Expanded(child: Container(color: Colors.white));
}
}
class AdsWidget extends StatelessWidget {
Widget build(BuildContext context) {
return Expanded(child: Container(color: Colors.red));
}
}
Now, depending on the layout, we could shows these, for example, in a Column
or in a Row
.
class PhoneLayout extends StatelessWidget {
Widget build(BuildContext context) {
return Column(children: [AdsWidget(), NewsWidget(), MenuWidget()]);
}
}
class DesktopLayout extends StatelessWidget {
Widget build(BuildContext context) {
return Row(children: [MenuWidget(), NewsWidget(), AdsWidget()]);
}
}
When asking for the maxWidth
property of the BoxConstraints
in LayoutBuilder
, we are receiving the maximum possible width for a widget within the constraints that the LayoutBuilder
receives from the parent widget. That is, the maxWidth
property is defined based on the parent widget.
The following example outlines this behavior. The HomeScreen
widget contains two Expanded
widgets, each of which contains a LayoutBuilder
widget. The LayoutBuilder
widget shows the value of the maxWidth
property of the BoxConstraints
object within a Center
widget.
When you try out the above example, you'll notice that the values change when you adjust the width of the screen. The above example also demonstrates LayoutBuilder
within widgets beyond just setting the layout.
This behavior can also be problematic, if we're not careful. As LayoutBuilder
respects the width of the parent, in unbounded situations -- such as in the case of a Row
-- the maximum width can be infinite, as shown below.