enum Action { OK, Cancel }
class AlertDialogDemo extends StatefulWidget {
@override
_AlertDialogDemoState createState() => _AlertDialogDemoState();
}
class _AlertDialogDemoState extends State<AlertDialogDemo> {
String _choice = 'Nothing';
Future _openAlertDialog() async {
final action = await showDialog(
context: context,
barrierDismissible: false, // 若设置为false用户不能点击空白部分来关闭对话框
builder: (BuildContext context) {
return AlertDialog(
title: Text('AlertDialog'),
content: Text('Are you sure about this?'),
actions: <Widget>[
FlatButton(
child: Text('OK'),
onPressed: () {
Navigator.pop(context, Action.OK);
},
),
FlatButton(
child: Text('Cancel'),
onPressed: () {
Navigator.pop(context, Action.Cancel);
},
)
],
);
});
switch (action) {
case Action.OK:
setState(() {
_choice = 'OK';
});
break;
case Action.Cancel:
setState(() {
_choice = 'Cancel';
});
break;
default:
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('AlertDialogDemo'),
),
body: Container(
padding: EdgeInsets.all(16),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Your choice is: $_choice'),
SizedBox(
height: 16,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RaisedButton(
child: Text('Open AlertDialog'),
onPressed: _openAlertDialog,
)
],
)
],
),
),
);
}
}
image.png
网友评论