Bruno Dias
Bruno Dias

Reputation: 149

I need some guidance in the Future Asynchronous Calls with flutter and dart, sometimes things happen out of order

The following code works fine, because it return only a simple list, but in some cases that I need to do nested Firebase calls, I can't make things happen in the right order, and the main return statement comes incomplete. What can I do to improve my Future Asynchronous Calls?

Future<List<MyNotification>> getNotifications() async {
    var uid = await FirebaseAuth.instance.currentUser();

    List<MyNotification> tempNots = await Firestore.instance
        .collection("notifications")
        .where("targetUsers", arrayContains: uid.uid)
        .getDocuments()
        .then((x) {
      List<MyNotification> tempTempNots = [];
      if (x.documents.isNotEmpty) {
        for (var not in x.documents) {
          tempTempNots.add(MyNotification.fromMap(not));
        }
      }
      return tempTempNots = [];
    });
    return tempNots;
  }

Upvotes: 1

Views: 35

Answers (1)

Ali Bayram
Ali Bayram

Reputation: 7921

The most important thing; don't use then inside your async functions. I modified your code like this;

Future<List<MyNotification>> getNotifications() async {
  // Using the type definition is better.
  FirebaseUser user = await FirebaseAuth.instance.currentUser();

  // The return type of getDocuments is a QuerySnapshot
  QuerySnapshot querySnapshot = await Firestore.instance
      .collection("notifications")
      .where("targetUsers", arrayContains: user.uid)
      .getDocuments();

  List<MyNotification> tempTempNots = [];

  if (querySnapshot.documents.isNotEmpty) {
    for (DocumentSnapshot not in querySnapshot.documents) {
      tempTempNots.add(MyNotification.fromMap(not));
    }
  }
 return tempTempNots;
}

Upvotes: 2

Related Questions