I'm trying to return a bool value from the dialogbox but I do not understand why the value does not return as need. I have tried returning as a future value and returning the values together with context after popping the dialogbox.
final bool delete = await _showDialog();
print(delete);
Future<bool> _showDialog() {
bool result;
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Delete Appointment'),
content: Text(
'Are you sure? \nThis action cannot undo.',
style: TextStyle(
color: Colors.red,
fontSize: 20
),
),
actions: <Widget>[
FlatButton(
color: Colors.blue,
child: Text(
'CANCEL',
style: TextStyle(
color: Colors.white,
fontSize: 20
),
),
onPressed: () {
setState(() => result = false);
//print(result);
Navigator.pop(context, result);
return Future.value(result);
},
),
SizedBox(
width: 50,
),
FlatButton(
color: Colors.red,
child: Text(
'CONFIRM',
style: TextStyle(
color: Colors.white,
fontSize: 20
),
),
onPressed: () {
setState(() => result = true);
//print(result);
Navigator.pop(context, result);
return Future.value(result);
},
)
],
);
}
);
}
Here's a working example based on your code:
@override
Widget build(BuildContext context) {
return Container(
child: RaisedButton(onPressed: () async {
bool delete = await _showDialog(context);
print(delete);
})
);
}
Future<bool> _showDialog(context) {
return showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Delete Appointment'),
content: Text(
'Are you sure? \nThis action cannot undo.',
style: TextStyle(
color: Colors.red,
fontSize: 20
),
),
actions: <Widget>[
FlatButton(
color: Colors.blue,
child: Text(
'CANCEL',
style: TextStyle(
color: Colors.white,
fontSize: 20
),
),
onPressed: () {
Navigator.pop(context, false);
},
),
SizedBox(
width: 50,
),
FlatButton(
color: Colors.red,
child: Text(
'CONFIRM',
style: TextStyle(
color: Colors.white,
fontSize: 20
),
),
onPressed: () {
Navigator.pop(context, true);
},
)
],
);
}
);
}
For Return True
Navigator.of(context).pop(true);
For Return False
Navigator.of(context).pop(false);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With