Problem with filling the list after await command

Viewed 40

I have just started Flutter and I am stuck at a point. Below is some part of my function that first uploads provided pictures on firebase storage and then get their downloadable URLs and store them in the list of string. It should upload data to firestore with the list of URLs obtained from command list.add(imageUrl);

List<String> list = [];
imgList.forEach((element) async {
  final String filePath = element.path;
  final res =
      filePath.substring(filePath.lastIndexOf('im'), filePath.length);
  
  final ref = FirebaseStorage.instance.ref().child('images').child(res);
  await ref.putFile(File(element.path));
  final imageUrl = await ref.getDownloadURL();
  list.add(imageUrl);
});

final doc = FirebaseFirestore.instance.collection('cars').doc();

but it doesn't happens because the following line is called before filling the list due to await.

await doc.set({
'id': doc,
'img': list,
'price': 14450,
'make': 'Toyota',
'year': 2015`
});
1 Answers

Add await before imgList.forEach like

List<String> list = [];
await imgList.forEach((element) async {
  final String filePath = element.path;
  final res =
      filePath.substring(filePath.lastIndexOf('im'), filePath.length);
  
  final ref = FirebaseStorage.instance.ref().child('images').child(res);
  await ref.putFile(File(element.path));
  final imageUrl = await ref.getDownloadURL();
  list.add(imageUrl);
});

final doc = FirebaseFirestore.instance.collection('cars').doc();

edit

if this doesn't work then you may use for loop instead of forEach like

List<String> list = [];
    for(var element in imgList) {
      final String filePath = element.path;
      final res =
          filePath.substring(filePath.lastIndexOf('im'), filePath.length);
      
      final ref = FirebaseStorage.instance.ref().child('images').child(res);
      await ref.putFile(File(element.path));
      final imageUrl = await ref.getDownloadURL();
      list.add(imageUrl);
    }
    
    final doc = FirebaseFirestore.instance.collection('cars').doc();
Related