How to return a future<double> - Flutter

Viewed 793

I have a function called getAvctUODoss() which is supposed to return a Future<double> but it always return 0.0. If I add a print('sum'); in my forEach loop, I see that the code works, it's just for the return of it that I have some difficulties. I need the result of this function in another function but, because I can't go further because of this wrong return. I think my mistake is in the declaration of sum as a double but I have not idea how to fix this. I searched on Stack Overflow but I only found codes which print the values inside the forEach loop.

Thank you in advance for your precious help.

Here is the code of my two functions :

  Future<double> getAvctUODoss(String numDoss) async {
    double sum = 0.0; // I think the problem is in this declaration

    affaireCollection
        .document(numDoss.substring(0, 7))
        .collection('dossiers')
        .document(numDoss)
        .collection('rp')
        .getDocuments()
        .then((querySnapshot) {
      querySnapshot.documents.forEach((documentSnapshot) async {
        sum += await documentSnapshot.data['avct'] *
            (await documentSnapshot.data['UO_AT'] +
                await documentSnapshot.data['UO_CH']);
      });
    });
    return sum; //return always 0.0
  }

  Future updateAvctDoss(String numDoss) async {
    await affaireCollection
        .document(numDoss.substring(0, 7))
        .collection('dossiers')
        .document(numDoss)
        .updateData({
      'avct': await getAvctUODoss(numDoss) / await getTotalUODoss(numDoss)
    });
  }
1 Answers

Change the function to the following:

  Future<double> getAvctUODoss(String numDoss) async {
    double sum = 0.0; 

    QuerySnapshot querySnapshot = await affaireCollection
        .document(numDoss.substring(0, 7))
        .collection('dossiers')
        .document(numDoss)
        .collection('rp')
        .getDocuments();
      querySnapshot.documents.forEach((documentSnapshot){
        sum += documentSnapshot.data['avct'] *
            (documentSnapshot.data['UO_AT'] +
                documentSnapshot.data['UO_CH']);
    });
    return sum;
  }

Since you declared the function async, then instead of using then(), use await to wait for the data to be fully retrieved and then sum will be updated and return the data.

Related