Flutter, how to use confirmDismiss in Dismissible?
Here is an example from the flutter repo.
Tested on 1.12 version of flutter.
Future<bool> _showConfirmationDialog(BuildContext context, String action) {
return showDialog<bool>(
context: context,
barrierDismissible: true,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Do you want to $action this item?'),
actions: <Widget>[
FlatButton(
child: const Text('Yes'),
onPressed: () {
Navigator.pop(context, true); // showDialog() returns true
},
),
FlatButton(
child: const Text('No'),
onPressed: () {
Navigator.pop(context, false); // showDialog() returns false
},
),
],
);
},
);
}
Add inside Dismissible widget:
confirmDismiss: (DismissDirection dismissDirection) async {
switch(dismissDirection) {
case DismissDirection.endToStart:
return await _showConfirmationDialog(context, 'archive') == true;
case DismissDirection.startToEnd:
return await _showConfirmationDialog(context, 'delete') == true;
case DismissDirection.horizontal:
case DismissDirection.vertical:
case DismissDirection.up:
case DismissDirection.down:
assert(false);
}
return false;
}
In the confirmDismiss
attribute you can return an AlertDialog()
(or whatever type of dialog you prefer) and then list the possible outcomes (e.g., delete and cancel) in buttons and return either true
(delete) or false
(cancel) which then determines if the item has to be removed or needs to stay in the list.
Example:
confirmDismiss: (DismissDirection direction) async {
return await showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text("Confirm"),
content: const Text("Are you sure you wish to delete this item?"),
actions: <Widget>[
FlatButton(
onPressed: () => Navigator.of(context).pop(true),
child: const Text("DELETE")
),
FlatButton(
onPressed: () => Navigator.of(context).pop(false),
child: const Text("CANCEL"),
),
],
);
},
);
},
You can extract the logic into a method to make the code more readable.