假设您有一个可能具有可变大小的父小部件。
例如:
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');
}
}
),
);
https://stackoverflow.com/questions/41558368/
相关文章:
visual-studio-code - 如何为 Flutter 模拟器的 Visual Studi
Flutter 在极端情况下对齐两项 - 一项在左侧,一项在右侧
flutter - 如何在 Flutter 中设置按钮的宽度和高度?
angular - NativeScript 与 Flutter
flutter - 遍历列表以在 Flutter 中呈现多个小部件?
flutter - 如何覆盖 Flutter 中的 “Back” 按钮?
flutter - 从 StatefulWidget 外部控制状态
flutter - 使用不包含 Navigator 的上下文请求的 Navigator 操作