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指定宽度