如何将 showDialog 与 await 一起使用



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

不确定是否有更好的方法,但以下方法似乎有效。请注意调用 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("结构化以便可以在一个功能中完成"),如果您不想提供帮助,那就离开。

最新更新