【问题标题】:Autoclose dialog in FlutterFlutter 中的自动关闭对话框
【发布时间】:2020-04-19 15:50:40
【问题描述】:

我想在打开几秒钟后自动关闭对话框。我找到的解决方案是调用 Navigator.of(context).pop(); 延迟并且它有效。但是如果我在执行 Navigator.pop 命令之前手动关闭它(通过单击外部),就会出现问题。然后 Navigator.pop 只是关闭应用程序,我只看到一个黑屏。 我需要一种方法来消除关闭对话框时的延迟或找到其他解决方法。

showDialog(
  context: context,
  builder: (BuildContext builderContext) {
    Future.delayed(Duration(seconds: 5), () {
      Navigator.of(context).pop();
    });

    return AlertDialog(
      backgroundColor: Colors.red,
      title: Text('Title'),
      content: SingleChildScrollView(
        child: Text('Content'),
      ),
    );
  }
);

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    您可以使用Timer 来实现此目的。您可以随时取消计时器。

    在你的类中声明一个计时器属性:

    Timer _timer;
    

    并更改您的 showDialog 代码,如:

    showDialog(
      context: context,
      builder: (BuildContext builderContext) {
        _timer = Timer(Duration(seconds: 5), () {
          Navigator.of(context).pop();
        });
    
        return AlertDialog(
          backgroundColor: Colors.red,
          title: Text('Title'),
          content: SingleChildScrollView(
            child: Text('Content'),
          ),
       );
      }
    ).then((val){
      if (_timer.isActive) {
        _timer.cancel();
      }
    });
    

    【讨论】:

      【解决方案2】:

      在这种情况下,您使用的是错误 context

      尝试在“pop”中更改您正在使用的context

      你有这个BuildContext builderContext,使用 那个 builderContext 像:

      Navigator.of(builderContext).pop();
      

      【讨论】:

      • 你能告诉我有什么区别吗?在此先感谢...
      【解决方案3】:

      您可以使用 Timer 使用不同的方式执行 pop() 请求

      _timer = Timer(Duration(seconds: _timerTimeoutInterval), () {
          Navigator.of(context).pop();
      });
      

      如果你想取消定时器,你可以这样调用:

      if (_timer != null && _timer.isActive) {
        _timer.cancel();
      }
      

      【讨论】:

      • 您可以通过创建按钮并在该按钮的 onPress 回调中执行 Navigator pop 方法来手动关闭它。
      • 是的,但我想通过点击外部来关闭它。
      • 啊抱歉,我读错了问题。为了关闭对话框并取消弹出的执行,您需要使用计时器,可以按需取消。我将编辑我的初始答案。
      猜你喜欢
      • 2013-07-26
      • 1970-01-01
      • 1970-01-01
      • 2012-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-25
      • 1970-01-01
      相关资源
      最近更新 更多