0

I'm using firebase cloud firestore

inside a Future function I have this

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

'completed' printed before 'done' how to make it the opposite? how to await for the forEach function to end first then proceed

and even if I moved print('complete'); after the whole try catch block it doesn't work either so is there a way to wait try catch block?

Christopher Moore
  • 15,626
  • 10
  • 42
  • 52

1 Answers1

3

You can use Future.foreach OR Future.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);
          });
    }
Sam Chan
  • 1,665
  • 4
  • 14