flutter使用Flex,Expanded时,约束问题(constraintsError)

文档链接:https://flutter.cn/docs/development/ui/layout/box-constraints

Flex 在无边界约束条件下,不能将子 widget 的flex属性设置为 0(默认值)以外的任何值。
这意味着当一个 flex 框嵌套在另外一个 flex 框或者嵌套在可滚动区域内(无边界约束)时,不能使用 Expanded(默认flex=1)。如果这样做了,就会收到异常。

🙁 错误写法

// 错误写法,内层Column垂直方向无边界约束,子组件Expanded不能使用
Widget build(BuildContext context) {
    return Column(
      children: [
        Column(
          children: [
            Expanded(
              child: Container(
                color: Colors.amber
              )
            ),
            Expanded(
              child: Container(
                color: Colors.cyanAccent
              )
            )
          ],
        ),
      ],
    );
  }

直观地从组件树看(我注释掉了Expanded,否则会抛出constraintsError)。
在这里插入图片描述

其实,把Expanded的flex设置成0,然后Container给定高度也能用但不推荐,这样Expanded也没意义了

😃 正确写法

  // 给内部Column添加垂直方向约束
  Widget build(BuildContext context) {
    return Column(
      children: [
        Container(
          height: 500.0,
          child: Column(
            children: [
              Expanded(
                child: Container(
                  color: Colors.amber
                )
              ),
              Expanded(
                child: Container(
                  color: Colors.cyanAccent
                )
              )
            ],
          ),
        ),
      ],
    );
  }

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值