Reputation: 512
The problem
So I have an AlertDialog in my flutter app, and it has two buttons: yes
and no
.
No matter which button is clicked, I want the pop up to be dismissed, however I also want to run some code if yes
is pressed.
My code
showDialog(context: context, builder: (_) => AlertDialog(
title: Text("Delete?"),
content: Text("Do you want to delete this task?"),
actions: [
MaterialButton(child: Text("Yes"),onPressed: () => Navigator.pop(context)),
MaterialButton(child: Text("No"), onPressed: () => Navigator.pop(context)),
],
), barrierDismissible: true);
I would appreciate anyone's help
Upvotes: 1
Views: 59
Reputation: 2511
Try this
actions: [
MaterialButton(child: Text("Yes"),onPressed: () {
//do something
Navigator.pop(context))
}),
MaterialButton(child: Text("No"), onPressed: () => Navigator.pop(context)),
],
Upvotes: 1
Reputation: 7328
You can simply add a value when you call your Navigator.pop
which will be returned through the Future
from showDialog
. Here is a code sample:
showDialog<bool>(
context: context,
builder: (_) => AlertDialog(
title: Text("Delete?"),
content: Text("Do you want to delete this task?"),
actions: [
MaterialButton(child: Text("Yes"),onPressed: () => Navigator.pop(context, true)),
MaterialButton(child: Text("No"), onPressed: () => Navigator.pop(context, false)),
],
),
barrierDismissible: true,
).then((bool hasTappedOnYes) {
if (hasTappedOnYes) {}
else {}
});
Upvotes: 1
Reputation: 53
This is the way I've solved the same issue. I'm not sure if there is a cleaner way of doing it
bool yesPressed = false;
showDialog(
context: context,
builder: (_) => AlertDialog(
title: Text("Delete?"),
content: Text("Do you want to delete this task?"),
actions: [
MaterialButton(
child: Text("Yes"),
onPressed: () {
yesPressed = true;
Navigator.pop(context);
}),
MaterialButton(
child: Text("No"),
onPressed: () => Navigator.pop(context)),
],
),
barrierDismissible: true)
.then((value) {
if (yesPressed) {
// Do something
}
});
Upvotes: 1