紧约束
ConstrainedBox 约束组件
constraints
通过maxWidth
maxHeight
,来设置子组件最大约束
void main() {
runApp(build());
}
Widget build() {
return MaterialApp(
home: Scaffold(
body: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(
maxWidth: 200,
maxHeight: 200,
),
child: Container(
color: Colors.amber,
width: 50,
height: 50,
),
),
),
),
);
}
显示了一个 50 x 50 的 Container
- 我们加上
minWidth
minHeight
void main() {
runApp(build());
}
Widget build() {
return MaterialApp(
home: Scaffold(
body: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(
minWidth: 100,
minHeight: 100,
maxWidth: 200,
maxHeight: 200,
),
child: Container(
color: Colors.amber,
width: 10,
height: 10,
),
),
),
),
);
}
这时候 尺寸强制被设置为了 100 * 100
- 查看约束情况
紧约束定义
它的最大/最小宽度是一致的,高度也一样。
- 通过 BoxConstraints.tight 可以设置紧约束
void main() {
runApp(build());
}
Widget build() {
return MaterialApp(
home: Scaffold(
body: Center(
child: ConstrainedBox(
constraints: BoxConstraints.tight(const Size(100, 100)),
child: Container(
color: Colors.amber,
width: 10,
height: 10,
),
),
),
),
);
}
- 宽高约束都被设置成了 100