文档链接:https://flutter.cn/docs/development/ui/layout/box-constraints
Flex 在无边界约束条件下,不能将子 widget 的flex属性设置为 0(默认值)以外的任何值。
这意味着当一个 flex 框嵌套在另外一个 flex 框或者嵌套在可滚动区域内(无边界约束)时,不能使用 Expanded(默认flex=1)。如果这样做了,就会收到异常。
🙁 错误写法
// 错误写法,内层Column垂直方向无边界约束,子组件Expanded不能使用
Widget build(BuildContext context) {
return Column(
children: [
Column(
children: [
Expanded(
child: Container(
color: Colors.amber
)
),
Expanded(
child: Container(
color: Colors.cyanAccent
)
)
],
),
],
);
}
直观地从组件树看(我注释掉了Expanded,否则会抛出constraintsError)。
其实,把Expanded的flex设置成0,然后Container给定高度也能用但不推荐,这样Expanded也没意义了
😃 正确写法
// 给内部Column添加垂直方向约束
Widget build(BuildContext context) {
return Column(
children: [
Container(
height: 500.0,
child: Column(
children: [
Expanded(
child: Container(
color: Colors.amber
)
),
Expanded(
child: Container(
color: Colors.cyanAccent
)
)
],
),
),
],
);
}