【布局 Widget】 Flutter SizedBox

Flutter Sizedbox 是一个 布局组件,用来给 child 添加 tight 约束的,也可以用来添加空白。

width,height是 Sizedbox 的参数

 BoxConstraints get _additionalConstraints {
    return BoxConstraints.tightFor(width: width, height: height);
 }
final BoxConstraints constraints = this.constraints;
if (child != null) {
  child!.layout(_additionalConstraints.enforce(constraints),
      parentUsesSize: true);
  size = child!.size;
} else {
  size = _additionalConstraints.enforce(constraints).constrain(Size.zero);
}

enforce 方法根据 _additionalConstraints 返回一个新约束,新约束保证在参数 constraints 的范围之内。

以上就是 SizedBox 的布局逻辑,通过代码我们分析一下 child constrains, SizedBox size。

child 的 constrains

constrains 是 tight ,SizedBox 透传 constrains 给 child。

constrains 是 loose,width 为空,SizedBox 透传 minWidth,maxWith 给 child;height为空,SizedBox 透传 minHeight,maxHeight 给 child。

constrains 是 loose,width 不为空, 在 constrains 范围内 给 child 的 width tight 约束;height 不为空 在 constrains 范围内 给 child 的 height tight 约束。

确定自己的大小

如果有 child ,和 child 一样大。

没有child ,constrains 是 tight ,大小为约束最小值。

没有child ,constrains 是 loose,在约束范围内由 width,height 参数指定。

SizedBox 的命名构造函数们

SizedBox 虽然本身很简单,但它命名构造函数确实不少。我们平时用的时候大多忽略了这些命名构造函数,所以应该先混个脸熟,用这些命名构造函数还是有好处的,可以增加代码的可读性。

SizedBox.expand

使 SizedBox 获得最大 Size,也就是和父 widget 一样大。

const SizedBox.expand({ super.key, super.child })
    : width = double.infinity,
      height = double.infinity;

SizedBox.shrink

让 SizedBox 尽量小。

const SizedBox.shrink({ super.key, super.child })
    : width = 0.0,
      height = 0.0;

SizedBox.fromSize

通过 size 来构造 SizedBox。

SizedBox.fromSize({ super.key, super.child, Size? size })
    : width = size?.width,
      height = size?.height;

SizedBox.square

保证 SizedBox 是一个正方形。

  const SizedBox.square({super.key, super.child, double? dimension})
    : width = dimension,
      height = dimension;

应用场景

为 child 提供 tight 约束。

当指定了 width,height 参数后,child 就获得了宽高的 tight 约束。保证 child 有固定大小。这对于固定布局非常有用。

为 children 之间提供空白。

可以用 padding 添加空白,但那样会增加一层嵌套,用 SizedBox 充当空白看起来更好一些。

占位

只是用来占位,比如 Spacer 中的 child 用的就是 SizedBox.shrink。

class Spacer extends StatelessWidget {

  const Spacer({super.key, this.flex = 1})
    : assert(flex != null),
      assert(flex > 0);
  final int flex;
  
  
  Widget build(BuildContext context) {
    return Expanded(
      flex: flex,
      child: const SizedBox.shrink(),
    );
  }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IAM17前端

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值