federico D'Armini
federico D'Armini

Reputation: 311

Return List<User> from Firestore Flutter

I want to return a List<User> from Firestore, the problem is that the result of this interrogation is an empty list. I'm sure that the problem is how I handled the process of add items to an existing list, maybe I didn't wait for them or something like that.

I'll show the code :

List<User> readUsers(String path, int limit) {
    List<User> users = [];
    FirebaseFirestore.instance
        .collection(path)
        .limit(limit)
        .get()
        .then((snapshot) {
      if (snapshot == null)
        print("Snapshot is null");
      else {
        snapshot.docs.forEach((data) {
          User user = User(
            name: data['name'],
            id: data['id'],
          );
          users.insert(0, user);
        });
      }
    });
    if (users.isNotEmpty) {
      users.forEach((element) {
        element == null ? print("") : print(element.id);
      });
    } else {
      print("User is empty!");
    }
    return users;
  }

The result of this function is always a print of "User is empty".

EDIT : Data from this function must be stored inside a variable and values must be printed like :

try {
List<User> users;
        widget.database
            .readUsers("users", 2)
            .then((value) => users = value);
        users.forEach((element) {
          print(element.id);
        });
      } catch (e) {
        print(e);
      }

Now the value of users is still null.

Upvotes: 0

Views: 1625

Answers (1)

Thierry
Thierry

Reputation: 8383

You have two problems in your code.

  1. Your Firebase call is async and does not finish before you test the emptiness of your List users. This is why your List<User> is always empty. You should define readUsers asasync, and await the QuerySnapshot
  2. If you check the API of cloud_firestore, you will see that your snapshot.docs is a List<QueryDocumentSnapshot>. The data should be accessed with the method data().

Try this:

Future<List<User>> readUsers(String path, int limit) async {
  final snapshot =
      await FirebaseFirestore.instance.collection(path).limit(limit).get();
  return snapshot.docs
      .map(
        (doc) => User(
          id: doc.data()['id'],
          name: doc.data()['name'],
        ),
      )
      .toList();
}

Upvotes: 1

Related Questions