显示对话框SimpleDialog
class SimpleDialogDemo extends StatefulWidget {
@override
_SimpleDialogDemoState createState() => _SimpleDialogDemoState();
}
class _SimpleDialogDemoState extends State<SimpleDialogDemo> {
String _choice = '';
// 弹出对话框
Future _openSimpleDialog() async {
final option = await showDialog(
context: context,
builder: (BuildContext context) {
return SimpleDialog(
title: Text('你想做什么呢?'),
children: <Widget>[
SimpleDialogOption(
child: Text('吃饭'),
onPressed: () { Navigator.pop(context, '吃饭');},
),
SimpleDialogOption(
child: Text('睡觉'),
onPressed: () { Navigator.pop(context, '睡觉');},
),
SimpleDialogOption(
child: Text('打豆豆'),
onPressed: () { Navigator.pop(context, '打豆豆');},
),
],
);
}
);
if (option != null) {
setState(() {
_choice = option;
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('SimpleDialog'), elevation: 0.0,),
body: Container(
padding: EdgeInsets.all(16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('我想。。。$_choice'),
],
),
),
floatingActionButton: FloatingActionButton(onPressed: _openSimpleDialog, child: Icon(Icons.format_list_numbered),),
);
}
}
提示对话框AlertDialog
class AlertDialogDemo extends StatefulWidget {
@override
_AlertDialogDemoState createState() => _AlertDialogDemoState();
}
class _AlertDialogDemoState extends State<AlertDialogDemo> {
String _choice = '';
// 弹出提示对话框
Future _openAlertDialog() async {
final action = await showDialog(
context: context,
barrierDismissible: false, // 如果要求用户必须点击对话框中的按钮才能让对话框消失,那么就设置这个属性为false
builder: (BuildContext context) {
return AlertDialog(
title: Text('提示'),
content: Text('你要吃冰淇淋吗?'),
actions: <Widget>[
FlatButton(onPressed: () { Navigator.pop(context, 'cancle'); }, child: Text('取消')),
FlatButton(onPressed: () { Navigator.pop(context, 'sure'); }, child: Text('确定')),
],
);
}
);
setState(() {
if (action == 'cancle') {
_choice = '不吃冰淇淋';
} else if (action == 'sure') {
_choice = '吃冰淇淋';
}
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('AlertDialog'), elevation: 0.0,),
body: Container(
padding: EdgeInsets.all(16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('我的选择是$_choice'),
SizedBox(height: 20,),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RaisedButton(child: Text('打开提示对话框'), onPressed: _openAlertDialog),
],
),
],
),
),
);
}
}
网友评论