Flutter提供了两种类型的对话框:SimpleDialog和AlertDialog。SimpleDialog是一个可以显示附加的提示或操作的简单对话框,AlertDialog则是一个会中断用户操作的对话框,需要用户确认的对话框,下面用代码来说明其用法
import 'package:flutter/material.dart';
main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Test',
home: new Scaffold(
appBar: new AppBar(
title: new Text('Test')
),
// body: new MyAlertDialogView()
body: new MySimpleDialogView(),
),
);
}
}
class MyAlertDialogView extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new RaisedButton(
child: new Text('显示AlertDialog'),
onPressed: () {
showDialog<Null>(
context: context,
barrierDismissible: false, // 不能点击对话框外关闭对话框,必须点击按钮关闭
builder: (BuildContext context) {
return new AlertDialog(
title: new Text('提示'),
content: new Text('微软重申Windows 7将在2020年1月到达支持终点,公司希望利用这个机会说服用户在最新更新发布之前升级到Windows 10。'),
actions: <Widget>[
new FlatButton(
child: new Text('明白了'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
},
);
}
}
class MySimpleDialogView extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new RaisedButton(
child: new Text('显示SimpleDialog'),
onPressed: () {
showDialog(
context: context,
builder: (BuildContext ctx) {
return new SimpleDialog(
title: new Text('这是SimpleDialog'),
children: <Widget>[
new SimpleDialogOption(
onPressed: () { Navigator.pop(context); },
child: const Text('确定'),
),
new SimpleDialogOption(
onPressed: () { Navigator.pop(context); },
child: const Text('取消'),
),
],
);
}
);
},
);
}
}
上面的代码分别展示了SimpleDialog和AlertDialog的基本用法。需要注意的是,这里并没有直接将按钮和显示对话框的逻辑写到MyApp类中,而是分两个StatelessWidget来写的,如果你直接将按钮及显示对话框的逻辑写到MyApp的build方法里,是会报错的,具体报错信息为:
Navigator operation requested with a context that does not include a Navigator.
意思是导航操作需要一个不包含Navigator的上下文对象,而如果我们将showDialog的逻辑写到MyApp的build方法中时,使用的是MaterialApp的上下文对象,这个上下文对象是包含Navigator的,所以就会报错。上面的代码在模拟器中运行效果如下图