Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

flutter - How can I layout widgets based on the size of the parent?

Let's say you have a parent widget that might 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 to have the child of the parent container render something different based on the size that it's given.

Think of responsive design breakpoints, if the width is over X use this layout, if the width is under X use that layout.

What's the best way to do this in Flutter?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You will want to use the LayoutBuilder widget which will build at layout time and provides the parent widget's constraints.

The LayoutBuilder takes in a build() function which has the the standard BuildContext along with the BoxConstraints as parameters that can be used to help dynamically render widgets based on size.

Let's build a simple example of widget that renders "LARGE" if the parent width is greater than 200px and "SMALL" if the parent width is less or equal to that.

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');
      }
    }
  ),
);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...