问题描述
让我们说您有一个可能具有可变大小的父窗口小部件。
Lets say you have a parent widget that might have variable size.
例如:
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 to render something different based on what the size that it's given.
考虑响应式设计断点,如果宽度超过X,则使用此布局;如果宽度低于X,则使用该布局。
在Flutter中做到这一点的最佳方法是什么?
What's the best way to do this in Flutter?
推荐答案
想要使用小部件来构建 在布局时,并提供父窗口小部件的约束。
You will want to use the LayoutBuilder widget which will build at layout time and provides the parent widget's constraints.
LayoutBuilder
接受一个 build()
函数,该函数具有标准的以及作为参数
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.
让我们构建一个简单的示例,该示例具有以下功能:如果父级宽度大于200px,则为大;如果父级宽度小于或等于200px,则为小。
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');
}
}
),
);
这篇关于如何根据父项的大小来布局小部件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!