Flutter 中 ConstrainedBox、BoxConstraints 的使用详解 | Flutter Widgets
前言
上篇我们聊了Flutter中的 SizedBox、FractionallySizedBox、LimitedBox、AspectRatio 这个 Box 组件的使用,这篇我们单独聊聊 ConstrainedBox
(约束盒子) 。
ConstrainedBox(约束盒子)
为啥要单独拿出来聊呢?
因为更加的控制灵活并且之后我们聊 Container、Button、Dialog
等等可能都会看到他的身影,这里一篇把他聊透了,之后看到就是走心回忆一下即可知道源码的意思了。
看源码
这里看到
2295
行是一个必传参数 constraints
,剩下就是一个 child
这个不用多说了,就是子项 Widget,看起来是不是非常的简单?下面我们来使用一下吧。
🤔思考一下
如果要实现下面的效果,你会怎么做呢?
- 最小高度 40
- 宽度随着文字个数变化
- 超过最大宽度文字换行
BoxConstraints(盒子约束)
现在我们就开始看看使用 ConstrainedBox
如何实现吧!先聊聊他的必传参数 constraints
,也是本文的重点哦
看源码
这里看到
BoxConstraints
的源码也非常简单,就是继承自 Constraints
然后有最小和最大的宽高,最小值都是0,最大值都是无限大。
构造函数的使用
ConstrainedBox(
// BoxConstraints 构造
constraints: BoxConstraints(
// 最小高度 40
minHeight: 40,
// 最大高度 100
maxHeight: 100,
// 最小宽度 40
minWidth: 40,
// 最小宽度 300
maxWidth: 300,
),
child: BoxWidget(
text: "ZeroFlutter 聊 ConstrainedBox",
),
)
这里我们只需要这样简单的设置就可以满足开头的需求了。
- 看效果
这里 BoxConstraints 的最基本的 4 个参数就简单使用完毕了,下面就会围绕这 4 个参数变换各种快捷函数了。
BoxConstraints.expand(展开约束)
- 看源码
设置约束宽高,如果没设置就为无限大,最大和最小宽高相等
- 上代码
ConstrainedBox(
// BoxConstraints 展开
constraints: BoxConstraints.expand(width: 300, height: 100),
child: BoxWidget(
text: "ZeroFlutter 聊 ConstrainedBox",
),
)
- 看效果
这里为了效果我添加了对比图,可以看到 BoxWidget 的宽高就是我们设置的宽高,并且展开到最大了。
BoxConstraints.loose(松约束)
- 看源码
设置约束大小,最小宽高为 0,最大宽高为设置大小的宽高
- 上代码
ConstrainedBox(
// BoxConstraints 松的
constraints: BoxConstraints.loose(Size(300, 100)),
child: BoxWidget(
text: "ZeroFlutter 聊 ConstrainedBox",
),
)
- 看效果
上上面的展开是明显的对比,这里最小按照 0 走了,所以大小是子类的大小
BoxConstraints.tight(紧约束)
- 看源码
设置约束大小,最小宽高和最大宽高都为设置大小的宽高
- 上代码
ConstrainedBox(
// BoxConstraints 紧的
constraints: BoxConstraints.tight(Size(300, 100)),
child: BoxWidget(
text: "ZeroFlutter 聊 ConstrainedBox",
),
)
- 看效果
BoxConstraints.tightForFinite(有限紧约束)
- 看源码
设置了非无限宽高,则等于 BoxConstraints.tight(紧约束) 未设置宽高(默认无限宽高),则等于最小宽高为0,最大宽高为无限
- 上代码
ConstrainedBox(
// BoxConstraints 紧的无限制
constraints: BoxConstraints.tightForFinite(height: 100),
// constraints: BoxConstraints.tightForFinite(width: 300),
child: BoxWidget(
text: "ZeroFlutter 聊 ConstrainedBox",
),
)
- 看效果
| height: 100 | width: 300 |
| :---: | :---: |
|
|
|
对象方法
我们创建一个 BoxConstraints
对象换可以,使用对象方法进行转换,比如这样,我将限定宽高的转换为松约束
ConstrainedBox(
// BoxConstraints 构造,转换为松约束
constraints: BoxConstraints(
minHeight: 40,
maxHeight: 100,
minWidth: 40,
maxWidth: 300,
).loosen(),
child: BoxWidget(
text: "ZeroFlutter 聊 ConstrainedBox",
),
)
- 看效果
| 转换前 | 转换后 |
| :---: | :---: |
|
|
|
其他常用方法
.loosen() | 返回一个新的松约束 |
---|---|
.flipped | 返回一个宽高调换的新约束 |
.normalize() | 返回一个 isNormalized 的新约束 |
widthConstraints() | 返回一个仅有宽度约束的新约束 |
heightConstraints() | 返回一个仅有高度约束的新约束 |
源码仓库
基于 Flutter 🔥 最新版本
参考链接
关注专栏
- 此文章已收录到下面👇 的专栏,可以直接关注
- 更多文章继续阅读|系列文章持续更新
👏 欢迎点赞➕收藏➕关注,有任何问题随时在下面👇评论,我会第一时间回复哦
转载自:https://juejin.cn/post/6978480197964136484