【问题标题】:How can I use showDialog with await如何将 showDialog 与等待一起使用
【发布时间】:2019-06-26 16:45:49
【问题描述】:

我有三个 showDialog 的例子。我认为 _showAlert1 是正确的,但是它使用 2 个函数来实现它。 _showAlert2 也有效,但我认为它不正确,因为我认为 showDialog 是异步的,并且我认为此函数依赖于足够时间显示的对话框。 _showAlert3 不起作用,因为对话框停留在屏幕上并且不清除。

如果 _showAlert2 虽然由于上述原因有效但不正确,有人可以告诉我应该如何构建它,以便可以在一个函数中完成。

示例:

void _showAlert0(BuildContext context, String text, int seconds) async {
    return await showDialog(
        barrierDismissible: false,
        context: context,
        builder: (context) => AlertDialog(
              title: Text("Error"),
              content: Text(text),
            ));
  }

  void _showAlert1(BuildContext context, String text, int seconds) async {
    _showAlert0(context, text, seconds);
    await Future.delayed(Duration(seconds: seconds));
    Navigator.of(context).pop(true);
  }

  void _showAlert2(BuildContext context, String text, int seconds) async {
    showDialog(
        barrierDismissible: false,
        context: context,
        builder: (context) => AlertDialog(
              title: Text("Error"),
              content: Text(text),
            ));
    await Future.delayed(Duration(seconds: seconds));
    Navigator.of(context).pop(true);
  }

void _showAlert3(BuildContext context, String text, int seconds) async {
    await showDialog(
        barrierDismissible: false,
        context: context,
        builder: (context) => AlertDialog(
              title: Text("Error"),
              content: Text(text),
            ));
    await Future.delayed(Duration(seconds: seconds));
    Navigator.of(context).pop(true);
}

【问题讨论】:

  • “这应该如何构建以便可以在一个函数中完成?”
  • 但是你想在这里做什么?看来您想自动弹出对话框?如果是这种情况,为什么不直接从对话构建器内部进行呢?只需在 AlertDialog 构建器中添加 future.delayed 并从那里弹出。只是不要await它。
  • 我想我已经非常清楚我想要实现的目标。 “这应该如何构建,以便可以在一个功能中完成?”发布答案并不难。如果您知道如何完成,为什么不发布答案,我会尝试一下?

标签: async-await flutter


【解决方案1】:

不确定是否有更好的方法,但以下似乎可行。请注意调用 showDialog() 时的“then”子句。

void _showAlert3(BuildContext context, String text, int seconds) async {
    showDialog(
        barrierDismissible: false,
        context: context,
        builder: (context) => AlertDialog(
              title: Text("Error"),
              content: Text(text),
            )).then((val) {});
    await Future.delayed(Duration(seconds: seconds));
    Navigator.of(context).pop(true);
  }

对于巨魔,RTFQ(“结构化以便可以在一个功能中完成”),如果您不想提供帮助,请离开。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-17
    • 1970-01-01
    • 2017-03-01
    相关资源
    最近更新 更多