Flutter系列之设置Dialog的宽度

Flutter中弹起对话框使用showDialog()函数,举个栗子:

showDialog(
      context: context,
      builder: (context) {
        return Dialog(
          child: Container(
            color: Colors.white,
            width: 50,
            height: 300,
            child: Center(
              child: Text(
                '测试dialog的宽度',
              ),
            ),
          ),
        );
      },
    );

你会发现,在dialog中的child设置的宽度不起作用,也无法宽度满屏显示,这是怎么回事呢?

这是因为Dialog的内部实现使用ConstrainedBox,并设置了最小宽度为280dp。

child: ConstrainedBox(
            constraints: const BoxConstraints(minWidth: 280.0),
            child: Material(
              color: backgroundColor ?? dialogTheme.backgroundColor ?? Theme.of(context).dialogBackgroundColor,
              elevation: elevation ?? dialogTheme.elevation ?? _defaultElevation,
              shape: shape ?? dialogTheme.shape ?? _defaultDialogShape,
              type: MaterialType.card,
              clipBehavior: clipBehavior,
              child: child,
            ),
          ),

所以child的宽度如果小于280是不起作用的,所以你想自定义宽度,需要在Dialog的外围再套一层UnconstrainedBox,用于抵消它原有的约束,代码如下:

showDialog(
      context: context,
      builder: (context) {
        return UnconstrainedBox(//在Dialog的外层添加一层UnconstrainedBox
          constrainedAxis: Axis.vertical,
          child: SizedBox(//再用SizeBox指定宽度
            width: 100,
            child: Dialog(
              insetPadding: EdgeInsets.zero,
              child: Container(
                color: Colors.white,
                height: 300,
                child: Center(
                  child: Text(
                    '测试dialog的宽度',
                  ),
                ),
              ),
            ),
          ),
        );
      },
    );

效果如图:

如果你想Dialog全屏显示,就要将Dialog的insetPadding设为0。代码演示:

showDialog(
      context: context,
      builder: (context) {
        return Dialog(
          insetPadding: EdgeInsets.zero,
          child: Container(
            color: Colors.white,
            height: 300,
            child: Center(
              child: Text(
                '测试dialog的宽度',
              ),
            ),
          ),
        );
      },
    );

效果如下:

总结:

设置Dialog的宽度可使用两种方法:

  • 设置Dialog的insetPadding
  • 使用UnconstrainedBox和SizeBox指定宽度

 

 

  • 9
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值