【问题标题】:How can I make alertDialog disappear automatically after few seconds in Flutter?如何在 Flutter 中让 alertDialog 在几秒钟后自动消失?
【发布时间】:2019-05-06 00:58:24
【问题描述】:

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

【问题讨论】:

  • Future<T>.delayed构造函数

标签: android dart flutter


【解决方案1】:

一个最小的例如:

它会在 5 秒后关闭 alertDialog

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

【讨论】:

  • 如果对话框barrierDismissible为真,会不会是延迟弹出的问题?
  • 这不是一个好的解决方案,因为在与用户请求 Future.delayed 关闭对话后开始工作并关闭另一个页面
【解决方案2】:

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;
});

【讨论】:

    【解决方案3】:

    您可能希望使用“SnackBar”来显示自动消失的通知。

    final snackBar = SnackBar(
      content: Text('This is where you put the notice.'),
      duration: Duration(seconds: 2),
    );
    Scaffold.of(context).showSnackBar(snackBar);
    

    【讨论】:

    • 嗨,我在频道管理员中尝试了这个,但 showSnackBar 已被弃用。
    猜你喜欢
    • 2013-08-26
    • 1970-01-01
    • 1970-01-01
    • 2020-10-18
    • 2019-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多