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

iyr7buue  于 2023-04-13  发布在  Flutter
关注(0)|答案(2)|浏览(173)

有3种方法可以解除AlertDialog(在我的示例中):
1.在其屏障外轻敲。('取消')
1.点击按钮A,将调用pop().('to proceed')
1.点击按钮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?
      });
rsl1atfo

rsl1atfo1#

您可以传递像Navigator.of(context).pop('something ')这样的数据,然后在.then中接收其值

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类,这样应该会更好。

m0rkklqb

m0rkklqb2#

您可以将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)
}

相关问题