假设您有一个可能具有可变大小的父小部件。
例如:
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作为可用于帮助根据大小动态呈现小部件的参数。
让我们构建一个简单的小部件示例,如果父宽度大于 200 像素,则呈现“LARGE”,如果父宽度小于或等于该宽度,则呈现“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');
}
}
),
);
关于flutter - 如何根据父级的大小布局小部件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41558368/