Flutter控件——布局控件:约束(二)限制子组件大小的组件

约束限制子组件大小的组件

ConstrainedBox

用于对子组件添加额外的约束。例如,如果你想让子组件的最小高度是80像素,你可以使用const BoxConstraints(minHeight: 80.0)作为子组件的约束。

box.dart 源码

class BoxConstraints extends Constraints {
  /// Creates box constraints with the given constraints.
  const BoxConstraints({
    this.minWidth = 0.0,
    this.maxWidth = double.infinity,
    this.minHeight = 0.0,
    this.maxHeight = double.infinity,
  }) 

示例

//一个背景颜色为红色的盒子,不指定它的宽度和高度:
Widget redBox = DecoratedBox(
  decoration: BoxDecoration(color: Colors.red),
);

//ConstrainedBox(
  constraints: BoxConstraints(
    minWidth: double.infinity, //宽度尽可能大
    minHeight: 50.0 //最小高度为50像素
  ),
  child: Container(
    height: 5.0,
    child: redBox ,
  ),
)

效果:将Container的高度设置为5像素,但是最终却是50像素,这正是ConstrainedBox的最小高度限制生效了。


SizedBox

basic.dart源码

class SizedBox extends SingleChildRenderObjectWidget {

  const SizedBox({ Key? key, this.width, this.height, Widget? child })
    : super(key: key, child: child);

  /// 创建一个长方体,该长方体将尽可能大。
  const SizedBox.expand({ Key? key, Widget? child })
    : width = double.infinity,
      height = double.infinity,
      super(key: key, child: child);

  /// 创建一个将尽可能小的长方体。
  const SizedBox.shrink({ Key? key, Widget? child })
    : width = 0.0,
      height = 0.0,
      super(key: key, child: child);

  /// Creates a box with the specified size.
  SizedBox.fromSize({ Key? key, Widget? child, Size? size })
    : width = size?.width,
      height = size?.height,
      super(key: key, child: child);

  /// 创建具有指定大小的长方体。
  const SizedBox.square({Key? key, Widget? child, double? dimension})
    : width = dimension,
      height = dimension,
      super(key: key, child: child);

  final double? width;

  final double? height;

SizedBox用于给子元素指定固定的宽高,如:

SizedBox(
  width: 80.0,
  height: 80.0,
  child: redBox
)

实际上SizedBox只是ConstrainedBox的一个定制,上面代码等价于:

ConstrainedBox(
  constraints: BoxConstraints.tightFor(width: 80.0,height: 80.0),
  child: redBox,
)

而BoxConstraints.tightFor(width: 80.0,height: 80.0)等价于:

BoxConstraints(minHeight: 80.0,maxHeight: 80.0,minWidth: 80.0,maxWidth: 80.0)

而实际上ConstrainedBox和SizedBox都是通过RenderConstrainedBox来渲染的,我们可以看到ConstrainedBox和SizedBox的
createRenderObject()方法都返回的是一个RenderConstrainedBox对象:

@override
RenderConstrainedBox createRenderObject(BuildContext context) {
  return RenderConstrainedBox(
    additionalConstraints: ...,
  );
}

UnconstrainedBox

  • UnconstrainedBox 的子组件将不再受到约束,大小完全取决于自己。
  • 任何时候子组件都必须遵守其父组件的约束。
  • 因此UnconstrainedBox依旧受父组件的约束。

其他的尺寸限制类容器

  • AspectRatio,它可以指定子组件的长宽比
  • LimitedBox 用于指定最大宽高
  • FractionallySizedBox 可以根据父容器宽高的百分比来设置子组件宽高等。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值