Material 库提供了三种基本对话框控件
- AlertDialog 通常用于提示型对话框
- SimpleDialog 通常用于列表型对话框
- Dialog 通常用于自定义布局元素的对话框
弹出对话框时,调用showDialog函数,将对话框控件传入,由于对话框本身是路由,所以关闭对话框时,需使用Navigator.of(context).pop()
除此外,还有一种iOS风格的基本对话框控件 CupertinoAlertDialog,用法与之类似,使用showCupertinoDialog函数显示,需要注意导入cupertino的包
按钮对话框
onPressed: () {
showDialog(
context: context,
builder: (BuildContext context) => AlertDialog(
title: const Text('标题'),
content: const Text('我是内容如果勒紧裤带健康肌肤克里斯丁就飞快的巨坑老师'),
actions: [
OutlinedButton(onPressed: (){print('取消');}, child: Text('取消')),
OutlinedButton(onPressed: (){print('确定');}, child: Text('确定')),
],
));
},
提示对话框
onPressed: () {
showDialog(
context: context,
builder: (BuildContext context) => const AlertDialog(
content: Text('我是内容如果勒紧裤带健康肌肤克里斯丁就飞快的巨坑老师'),
));
},
列表对话框
onPressed: () {
showDialog(context: context, builder: (BuildContext context) => SimpleDialog(
title: const Text('列表对话框'),
children: [
SimpleDialogOption(
onPressed: (){print('选择第一项');},
child: const Text('第一项内容'),
),
SimpleDialogOption(
onPressed: (){print('选择第er项');},
child: const Text('第er项内容'),
),
SimpleDialogOption(
onPressed: (){print('选择第3项');},
child: const Text('第3项内容'),
),
SimpleDialogOption(
onPressed: (){print('选择第4项');},
child: const Text('第4项内容'),
),
],
));
},
自定义对话框
onPressed: () {
showDialog(
context: context,
builder: (BuildContext context) => Dialog(
// child: Text('我是内容如果勒紧裤带健康肌肤克里斯丁就飞快的巨坑老师'),
child: Image.network('https://c-ssl.duitang.com/uploads/item/201812/01/20181201203342_KjwZR.jpeg'),
));
},
模态对话框
onPressed: () {
showModalBottomSheet(
context: context,
builder: (BuildContext context) {
return ListView.builder(
itemCount: 20,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text("$index", textAlign: TextAlign.center,),
onTap: () => Navigator.of(context).pop(),
);
},
);
},
);
},
iOS风格模态对话框
onPressed: () {
showCupertinoModalPopup(
context: context,
builder: (BuildContext context) {
return CupertinoActionSheet(
title: const Text('提示'),
message: const Text('这是一个iOS风格的模态对话框'),
actions: [
CupertinoActionSheetAction(
child: const Text('确定'),
onPressed: () {},
isDefaultAction: true,
),
CupertinoActionSheetAction(
child: const Text('暂时取消'),
onPressed: () {},
isDestructiveAction: true,
),
CupertinoActionSheetAction(
child: const Text('只是用一次'),
onPressed: () {},
isDestructiveAction: true,
),
],
);
}
);
},
这里有一个好用的Flutter弹框库
flutter_smart_dialog: ^3.0.12
其他对话框
- showAboutDialog 关于对话框
- showDatePicker 日期选择器
- showTimePicker 时间选择器
- showCupertinoModalPopup + CupertinoTimerPicker iOS 风格时间选择器
- showCupertinoModalPopup + CupertinoDatePicker iOS 风格日期选择器