如何检测AlertDialog是否通过在其屏障外点击或通过Flutter中的按钮回调而被驳回?



有三种方法可以取消AlertDialog(在我的例子中):

  1. 在屏障外敲击。('取消')
  2. 点击按钮a,将调用pop()。('继续')
  3. 点击按钮B,将调用pop()。("取消")

我希望在AlertDialog关闭后在then()回调中运行一些代码。这段代码将取决于它是如何关闭的。

注意:我使用then()回调,所以我可以检测是否AlertDialog被驳回而不是一个按钮。

这可能吗?

showDialog(context: context, builder: (context) => AlertDialog(
title: Text('Grant access'),
actions: [
/// Button 'A'
OutlinedButton(onPressed: (){
Navigator.of(context).pop();
/// Some more code
}, child: Text('Grant access')),
/// Button 'B'
OutlinedButton(onPressed: () {
Navigator.of(context).pop();
}, child: Text('Cancel'))
],
)).then((value) async {
// Code after closure. Can I detect what way the AlertDialog was dismissed?
});

你可以传递这样的数据Navigator.of(context).pop('something')然后在中接收它的值。然后

showDialog(context: context, builder: (context) => AlertDialog(
title: Text('Grant access'),
actions: [
OutlinedButton(onPressed: (){
Navigator.of(context).pop('Button A');
/// Some more code
}, child: Text('Grant access')),
OutlinedButton(onPressed: () {
Navigator.of(context).pop('Button B');
}, child: Text('Cancel'))
],
)).then((value) async {
// Check if the value returned from showDialog is null
if (value == null) {
// If value is null, it means that the dialog was closed by tapping outside
print('Dialog closed by tapping outside');
} else {
// If value is not null, it means that the dialog was closed with a value
// Print the value for debugging purposes
print('Dialog closed with value: $value');
}
});

但是我建议你创建一个带有回调的CustomDialog类,它应该会更好。

您可以将await关键字与showDialog()函数一起使用,然后检查函数返回的值来确定解雇方法。

var result = await showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text('Grant access'),
actions: [
OutlinedButton(
child: Text('Grant access'),
onPressed: () {
Navigator.of(context).pop('Granted');
},
),
OutlinedButton(
child: Text('Cancel'),
onPressed: () {
Navigator.of(context).pop('Cancelled');
},
),
],
),
);
if (result == 'Granted') {
// run code for dismissal by tapping button A
} else if (result == 'Cancelled') {
// run code for dismissal by tapping button B or outside barrier
} else {
// run code for dismissal by other means (e.g. back button)
}

最新更新