【Flutter】功能型组件之对话框详解
前言
对话框本质上也是UI布局,通常一个对话框会包含标题、内容,以及一些操作按钮,为此,Material库中提供了一些现成的对话框组件来用于快速的构建出一个完整的对话框。
接口描述
// 1. AlertDialog
const AlertDialog({
Key key,
// 对话框组件标题
this.title,
// 标题填充
this.titlePadding,
// 标题文本样式
this.titleTextStyle,
// 对话框内容组件
this.content,
// 内容的填充
this.contentPadding = const EdgeInsets.fromLTRB(24.0, 20.0, 24.0, 24.0),
// 内容文本样式
this.contentTextStyle,
// 对话框操作按钮组
this.actions,
// 对话框背景色
this.backgroundColor,
// 对话框的阴影
this.elevation,
// 对话框语义化标签(用于读屏软件)
this.semanticLabel,
// 对话框外形
this.shape,
}) : assert(contentPadding != null),
super(key: key);
代码示例
// 对话框详解(dialog)
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
// 1. AlertDialog,消息对话框
Future<bool> showDeleteConfirmDialog(context){
return showDialog<bool>(
context: context,
//点击对话框barrier(遮罩)时是否关闭它
barrierDismissible: false,
builder: (context){
return AlertDialog(
title: Text("提示"),
content: Text("您确定要删除当前文件吗?"),
actions: <Widget>[
FlatButton(
child: Text("取消"),
// 关闭对话框
onPressed: () => Navigator.of(context).pop(),
),
FlatButton(
child: Text("确定"),
onPressed: (){
// 关闭对话框并返回true
Navigator.of(context).pop(true);
},
),
],
);
}
);
}
// 2. SimpleDialog,列表对话框
Future<void> changeLanguageDialog(context) async{
int i = await showDialog<int>(
context: context,
builder: (context){
return SimpleDialog(
title: const Text("请选择语言"),
children: <Widget>[
SimpleDialogOption(
onPressed: (){
// 返回1
Navigator.pop(context, 1);
},
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 0),
child: const Text("中文简体"),
),
),
SimpleDialogOption(
onPressed: (){
// 返回2
Navigator.pop(context, 2);
},
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 6),
child: const Text("美国英语"),
),
),
],
);
}
);
if(i != null){
print("选择了:${i == 1 ? "中文简体" : "美国英语"}");
}
}
// 3. Dialog,对话框
Future<void> showListDialog(context) async{
int index = await showDialog(
context: context,
builder: (context){
var child = Column(
children: <Widget>[
ListTile(title: Text("请选择"),),
Expanded(
child: ListView.builder(
itemCount: 30,
itemBuilder: (BuildContext context, int index){
return ListTile(
title: Text("$index"),
onTap: () => Navigator.of(context).pop(index),
);
},
),
)
],
);
//使用AlertDialog会报错
// 实际上AlertDialog和SimpleDialog都使用了Dialog类。由于AlertDialog和SimpleDialog中使用了IntrinsicWidth来尝试通过子组件的实际尺寸来调整自身尺寸,
// 这就导致他们的子组件不能是延迟加载模型的组件(如ListView、GridView 、 CustomScrollView等)
// return AlertDialog(content: child);
return Dialog(child: child);
}
);
if (index != null) {
print("点击了:$index");
}
}
// 4. showGeneralDialog,自定义非Material风格对话框
Future<T> customDialog<T>({
@required BuildContext context,
bool barrierDismissible = true,
WidgetBuilder builder,
}){
final ThemeData theme = Theme.of(context, shadowThemeOnly: true);
//
return showGeneralDialog(
context: context,
pageBuilder: (BuildContext buildContext, Animation<double> animation, Animation<double> secondaryAnimation){
final Widget pageChild = Builder(builder: builder,);
return SafeArea(
child: Builder(builder: (BuildContext context){
return theme != null
? Theme(data: theme, child: pageChild)
: pageChild;
}),
);
},
barrierDismissible: barrierDismissible,
barrierLabel: MaterialLocalizations.of(context).modalBarrierDismissLabel,
// 自定义遮罩颜色
barrierColor: Colors.black87,
transitionDuration: const Duration(milliseconds: 150),
transitionBuilder: _buildMaterialDialogTransitions,
);
}
Widget _buildMaterialDialogTransitions(
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child){
// 使用缩放动画
return ScaleTransition(
scale: CurvedAnimation(
parent: animation,
curve: Curves.easeOut,
),
child: child,
);
}
Future<bool> showCustomDialog(context){
return customDialog<bool>(
context: context,
//点击对话框barrier(遮罩)时是否关闭它
barrierDismissible: false,
builder: (context){
return AlertDialog(
title: Text("提示"),
content: Text("您确定要删除当前文件吗?"),
actions: <Widget>[
FlatButton(
child: Text("取消"),
// 关闭对话框
onPressed: () => Navigator.of(context).pop(),
),
FlatButton(
child: Text("确定"),
onPressed: (){
// 关闭对话框并返回true
Navigator.of(context).pop(true);
},
),
],
);
}
);
}
// 5. 对话框状态管理
Future<bool> showDeleteConfirmDialog1(context) {
bool _withTree = false;
return showDialog<bool>(
context: context,
builder: (context){
return AlertDialog(
title: Text("提示"),
content: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text("您确定要删除当前文件吗?"),
Row(
children: <Widget>[
Text("同时删除子目录"),
// Checkbox(
// // 使用Checkbox组件
// value: _withTree,
// onChanged: (bool value){
// // 此时context为对话框UI的根Element,我们
// // 直接将对话框UI对应的Element标记为dirty
// (context as Element).markNeedsBuild();
// _withTree = !_withTree;
// },
// )
// 通过Builder来获得构建Checkbox的`context`,
// 这是一种常用的缩小`context`范围的方式
Builder(
builder: (BuildContext context) {
return Checkbox(
value: _withTree,
onChanged: (bool value) {
(context as Element).markNeedsBuild();
_withTree = !_withTree;
},
);
},
),
],
)
],
),
actions: <Widget>[
FlatButton(
child: Text("取消"),
onPressed: () => Navigator.of(context).pop(),
),
FlatButton(
child: Text("删除"),
onPressed: (){
// 执行删除操作
Navigator.of(context).pop(_withTree);
},
)
],
);
}
);
}
// 6. 底部菜单列表
Future<int> _showModalBottomSheet(context){
return showModalBottomSheet<int>(
context: context,
builder: (BuildContext context){
return ListView.builder(
itemCount: 30,
itemBuilder: (BuildContext context, int index){
return ListTile(
title: Text("$index"),
onTap: () => Navigator.of(context).pop(index),
);
}
);
}
);
}
// 7. 全屏菜单列表
PersistentBottomSheetController<int> _showBottomSheet(context){
return showBottomSheet<int>(
context: context,
builder: (BuildContext context){
return ListView.builder(
itemCount: 30,
itemBuilder: (BuildContext context, int index){
return ListTile(
title: Text("$index"),
onTap: (){
print("$index");
Navigator.of(context).pop();
}
);
}
);
}
);
}
// 8. Loading框,通过showDialog+AlertDialog实现
showLoadingDialog(context) {
showDialog(
context: context,
// 点击遮罩不关闭对话框
barrierDismissible: false,
builder: (context) {
return AlertDialog(
content: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
CircularProgressIndicator(),
Padding(
padding: const EdgeInsets.only(top: 26),
child: Text("正在加载,请稍后..."),
)
],
),
);
}
);
}
// 9. 自定义对话框长度
// 只使用SizedBox或ConstrainedBox是不行的,原因是showDialog中已经给对话框设置了宽度限制,可以使用UnconstrainedBox先抵消showDialog对宽度的限制,然后再使用SizedBox指定宽度。
showCustomLoadingDialog(context) {
showDialog(
context: context,
barrierDismissible: false,
builder: (context) {
return UnconstrainedBox(
constrainedAxis: Axis.vertical,
child: SizedBox(
width: 280,
child: AlertDialog(
content: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
CircularProgressIndicator(),
Padding(
padding: const EdgeInsets.only(top: 26.0),
child: Text("正在加载,请稍后..."),
)
],
),
),
),
);
}
);
}
// 10. Material风格的日历选择器
Future<DateTime> _showDatePicker(context) {
var date = DateTime.now();
return showDatePicker(
context: context,
initialDate: date,
firstDate: date,
lastDate: date.add(
// 未来30天可选
Duration(days: 30),
)
);
}
// 11. iOS风格的日历选择器
Future<DateTime> _showDatePicker2(context) {
var date = DateTime.now();
return showCupertinoModalPopup(
context: context,
builder: (ctx) {
return SizedBox(
height: 200,
child: CupertinoDatePicker(
mode: CupertinoDatePickerMode.dateAndTime,
minimumDate: date,
maximumDate: date.add(
Duration(days: 30),
),
maximumYear: date.year + 1,
onDateTimeChanged: (DateTime value) {
print(value);
},
),
);
},
);
}
class DialogWidgetRoute extends StatefulWidget{
_DialogWidgetRouteState createState() => _DialogWidgetRouteState();
}
class _DialogWidgetRouteState extends State<DialogWidgetRoute>{
@override
Widget build(BuildContext context){
return Scaffold(
appBar: AppBar(
title: Text("对话框"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
// AlertDialog
FlatButton(
color: Colors.green,
highlightColor: Colors.green,
splashColor: Colors.red,
child: Text("AlertDialog"),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20.0)),
onPressed: () async{
// 弹出对话框并等待其关闭
bool delete = await showDeleteConfirmDialog(context);
if(delete == null){
print("取消删除");
} else{
print("确认删除");
}
},
),
// SimpleDialog
FlatButton(
color: Colors.green,
highlightColor: Colors.green,
splashColor: Colors.red,
child: Text("SimpleDialog"),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20.0)),
onPressed: () async{
changeLanguageDialog(context);
},
),
// Dialog
FlatButton(
color: Colors.green,
highlightColor: Colors.green,
splashColor: Colors.red,
child: Text("Dialog"),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20.0)),
onPressed: () async{
showListDialog(context);
},
),
// customDialog
FlatButton(
color: Colors.green,
highlightColor: Colors.green,
splashColor: Colors.red,
child: Text("customDialog"),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20.0)),
onPressed: () async{
// 弹出对话框并等待其关闭
bool delete = await showCustomDialog(context);
if(delete == null){
print("自定义取消删除");
} else{
print("自定义确认删除");
}
},
),
// 对话框状态管理
FlatButton(
color: Colors.green,
highlightColor: Colors.green,
splashColor: Colors.red,
child: Text("对话框状态管理"),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20.0)),
onPressed: () async{
// 弹出对话框并等待其关闭
bool delete = await showDeleteConfirmDialog1(context);
if(delete == null){
print("取消删除");
} else{
print("确认删除");
}
},
),
// 底部菜单列表
RaisedButton(
child: Text("底部菜单列表"),
onPressed: () async{
int type = await _showModalBottomSheet(context);
print(type);
},
),
// Loading框
RaisedButton(
child: Text("Loading框"),
onPressed: () async{
showLoadingDialog(context);
},
),
// 自定义对话框长度
RaisedButton(
child: Text("自定义对话框长度"),
onPressed: () async{
showCustomLoadingDialog(context);
},
),
// Material风格的日历选择器
RaisedButton(
child: Text("Material风格的日历选择器"),
onPressed: () async{
_showDatePicker(context);
},
),
// iOS风格的日历选择器
RaisedButton(
child: Text("iOS风格的日历选择器"),
onPressed: () async{
_showDatePicker2(context);
},
),
],
),
),
);
}
}
总结
对话框最终都是由showGeneralDialog方法打开的,直接调用Navigator的push方法打开了一个新的对话框路由_DialogRoute,然后返回了push的返回值。可见对话框实际上正是通过路由的形式实现的,这也是为什么我们可以使用Navigator的pop 方法来退出对话框的原因。