How can I display widgets based on parent size?

Suppose you have a parent widget that can have a variable size.

For example:

var container = new Container( height: 200.0, // Imagine this might change width: 200.0, // Imagine this might change // Imagine content in this container will // depend on the parent container child: new Container(), ); 

And maybe you want the child parent container to display something different depending on what size it gave.

Think about the breakpoints of the breakpoint, if the width is greater than X, use this layout, if the width is under X, use this layout.

What is the best way to do this in Flutter?

+14
dart flutter
source share
1 answer

You will want to use the LayoutBuilder widget , which will be created during the layout and provides the limitations of the parent widget.

LayoutBuilder accepts a build() function that has a standard BuildContext along with BoxConstraints as parameters that can be used to dynamically render widgets depending on size.

Let's create a simple widget example that displays "LARGE" if the parent width is greater than 200px, and "SMALL" if the parent width is less than or equal to this.

 var container = new Container( // Toggling width from 100 to 300 will change what is rendered // in the child container width: 100.0, // width: 300.0 child: new LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { if(constraints.maxWidth > 200.0) { return new Text('BIG'); } else { return new Text('SMALL'); } } ), ); 
+24
source share

All Articles