0

I am trying to implement the function below but it gives me null.

To be specific, Future credit() is not updating the variable value. There is no problem with the database because if I put print(doc['value']) instead of value += doc['value'], I get the expected result. It seems, getCredit() is the one returning null.

Future credit() async {
    final FirebaseUser user = await FirebaseAuth.instance.currentUser();
    final String uid = user.uid;
    int value = 0;
    Firestore.instance
        .collection('entries')
        .where("uid", isEqualTo: uid)
        .where("type", isEqualTo: "+")
        .orderBy("time", descending: true)
        .snapshots()
        .listen((data) => data.documents.forEach((doc) => value += doc['value']));
    print(value); // doesnt update value
    return value;
  }

  int getCredit() {
    credit().then((value) {print(value);});
    credit().then((value) {return value;});  // return mot working
  }

Thanks!

2 Answers 2

2

try this:

Future<int> getCredit() async {
  return await  credit();
}
Sign up to request clarification or add additional context in comments.

Comments

0

Fixed it. It seems it was a problem with the scope of variable.

int cr = 0;
Future credit() async {
    final FirebaseUser user = await FirebaseAuth.instance.currentUser();
    final String uid = user.uid;
    Firestore.instance
        .collection('entries')
        .where("uid", isEqualTo: uid)
        .where("type", isEqualTo: "+")
        .orderBy("time", descending: true)
        .snapshots()
        .listen((data) => data.documents.forEach((doc) {cr = cr + doc['value'];}));

    print('$cr');
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.