如何在showwait中使用showDialog

时间:2019-02-02 07:00:01

标签: async-await flutter

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

1 个答案:

答案 0 :(得分:0)

不确定是否有更好的方法,但是以下方法似乎可行。请注意对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(“结构化,因此可以在一个功能中完成”),如果您不想要帮助,那就走开。

相关问题