ConstrainedBox
一个对其子组件施加额外约束的组件
举个例子,如果你想要给子组件添加最小50逻辑像素的高度,你可以使用const BoxConstraints(minHeight: 50.0)来施加约束。
示例
ConstrainedBox(
constraints: const BoxConstraints.expand(),
child: const Card(child: Text('Hello World!')),
)
这个代码片段可以让子组件通过BoxConstraints.expand来填充父组件的大小。使用SizedBox.expand同样可以达到相同的效果。
构造函数
ConstrainedBox.new({
Key? key,
required BoxConstraints constraints,
Widget? child
})
参数
| 参数名 | 参数类型 | 说明 |
|---|---|---|
| child | Widget? | 子组件 |
| constraints | BoxConstraints | 给子组件施加的约束 |
额外说明
BoxConstraints是用来描述尺寸边界的不可变对象,它只有4个维度的边界值。
| 字段名 | 类型 | 含义 |
|---|---|---|
| minWidth | double | 子组件最小宽度,默认值 0 |
| maxWidth | double | 子组件最大宽度,默认值infinity |
| minHeight | double | 子组件最小高度,默认值 0 |
| maxHeight | double | 子组件最大高度,默认值infinity |
快捷工厂构造函数
| 构造函数 | 等效写法 | 用途 |
|---|---|---|
| BoxConstraints() | 4个值都要写 | 通用 |
| BoxConstraints.tight(Size) | min == max == Size | 固定宽高 |
| BoxConstraints.tightFor(width: w, height: h) | min == max == w/h(可为null) | 固定宽或高 |
| BoxConstraints.expand({width, height}) | min == max == double.infinity (或给定值) | 占满父级 |
| BoxConstraints.loosen() | 把当前对象的min全改成0,max不变 | 解除下限 |
| BoxConstraints.copyWith() | 基于现有对象改某个值 | 局部调整 |