在Flutter中几秒钟后,如何使alertDialog自动消失?

Nav*_*een 6 android dart flutter

点击按钮时将显示一个alertDialog,并在几秒钟后自动消失。如何在Flutter中做到这一点?

Apo*_*leo 9

Future.delayed如果在触发 Future 之前关闭对话框,可能会导致一些问题。因此,如果您使用它,请注意 showDialog 不可barrierDismissible: false关闭,并且 AlertDialog 没有关闭它的按钮。

否则,您可以使用计时器:

Timer timer = Timer(Duration(milliseconds: 3000), (){
  Navigator.of(context, rootNavigator: true).pop();
});
showDialog(
  ... Dialog Code ...
).then((value){
  // dispose the timer in case something else has triggered the dismiss.
  timer?.cancel();
  timer = null;
});
Run Code Online (Sandbox Code Playgroud)


anm*_*ail 7

最小的例如:

alertDialog5秒后关闭。

           showDialog(
                      context: context,
                      builder: (context) {
                        Future.delayed(Duration(seconds: 5), () {
                          Navigator.of(context).pop(true);
                        });
                        return AlertDialog(
                          title: Text('Title'),
                        );
                      });
Run Code Online (Sandbox Code Playgroud)

  • 这不是一个好的解决方案,因为在关闭用户请求 Future.delayed 的对话框后开始工作并关闭另一个页面 (6认同)
  • 如果对话框的barrierDismissible为true,那么弹出延迟会出现问题吗? (2认同)