如何根据父项的大小来布局小部件?
问题内容:
假设您有一个父窗口小部件,其大小可能可变。
例如:
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(),
);
也许您想让父容器的子容器根据给定的大小呈现不同的内容。
考虑响应式设计断点,如果宽度大于X,则使用此布局;如果宽度小于X,则使用该布局。
在Flutter中执行此操作的最佳方法是什么?
问题答案:
您将要使用LayoutBuilder小部件,该小部件将 在布局时生成并提供父小部件的约束。
的LayoutBuilder
在需要build()
其具有标准功能BuildContext与沿BoxConstraints作为参数,可用于帮助动态地呈现基于尺寸的小部件。
让我们构建一个简单的小部件示例,如果父宽度大于200px,则呈现“ LARGE”,如果父宽度小于或等于200px,则呈现“ SMALL”。
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');
}
}
),
);