【问题标题】:Flutter await for try catch [duplicate]颤振等待尝试捕获[重复]
【发布时间】:2021-05-05 02:52:40
【问题描述】:

我正在使用 firebase cloud firestore

在 Future 函数中我有这个

try {
          categories.forEach((element) async {
            await FirebaseFirestore.instance.collection('Categories').add({
              'name': element[0],
              'imageUrl': element[1],
            });
            print('done');
          });
          print('complete');
        } catch (e) {
          CoolAlert.show(
              context: context,
              type: CoolAlertType.error,
              content: Text(e),
              text: "Upload Failed",
              onConfirmBtnTap: () {
                Navigator.pop(context);
                Navigator.pop(context);
              });
        }

在“完成”之前打印“完成” 如何使它相反? 如何等待 forEach 函数先结束然后继续

即使我在整个 try catch 块之后移动了print('complete'); ,它也不起作用 那么有没有办法等待 try catch 块?

【问题讨论】:

  • 不确定,但您是否尝试将 await 放在 categories.forEach((element) 之前?
  • 是的,它说“‘await’应用于‘void’,而不是‘Future’”

标签: flutter dart


【解决方案1】:

您可以使用Future.foreachFuture.doWhile

Future.doWhile

 int index = 0;
    try {
      Future.doWhile(() {
        if (index < categories.length) {
          await FirebaseFirestore.instance.collection('Categories').add({
            'name': categories[index][0],
            'imageUrl': categories[index][1],
          });
          print('done');
          index++;
          return true;
        } else {
          print('complete');
          return false;
        }
      });
    } catch (e) {
      CoolAlert.show(
          context: context,
          type: CoolAlertType.error,
          content: Text(e),
          text: "Upload Failed",
          onConfirmBtnTap: () {
            Navigator.pop(context);
            Navigator.pop(context);
          });
    }

Future.foreach:

try {
      Future.forEach(categories,(element) async {
        await FirebaseFirestore.instance.collection('Categories').add({
          'name': element[0],
          'imageUrl': element[1],
        });
        print('done');
      });
      print('complete');
    } catch (e) {
      CoolAlert.show(
          context: context,
          type: CoolAlertType.error,
          content: Text(e),
          text: "Upload Failed",
          onConfirmBtnTap: () {
            Navigator.pop(context);
            Navigator.pop(context);
          });
    }

【讨论】:

  • 非常感谢,我使用了 Future.forEach,它成功了。
猜你喜欢
  • 2021-06-10
  • 2021-03-28
  • 2022-01-26
  • 2018-04-20
  • 2020-10-25
  • 1970-01-01
  • 2020-09-01
  • 2023-04-07
  • 2021-05-29
相关资源
最近更新 更多