Vueer
Vueer

Reputation: 1500

Converting a forEach loop to a Future.forEach loop in Flutter

I try to convert a .forEach loop to a Future.forEach loop in flutter to wait for the loop. The element I want to loop is a snapshot from a Firebase Realtime Database.

My function looks like this:

Future<User> getUserByUid(String uid) async {
    DataSnapshot dataSnapshot =
        await databaseRef.orderByChild("uid").equalTo(uid).once();

    List user = List();

    dataSnapshot.value.forEach((key, value) async {
      User entry = await User.fromJson(value);
      await entry.setId(key);

      user.add(entry);
    });

    if (user.isNotEmpty) {
      return user[0];
    } else {
      return null;
    }
  }

I tried different ways, but I don't get the function to work.

First Try:

Future<User> getUserByUid(String uid) async {
    DataSnapshot dataSnapshot =
        await databaseRef.orderByChild("uid").equalTo(uid).once();

    List user = List();

    await Future.forEach(dataSnapshot.value, (element) {
      print(element);
    });

    if (user.isNotEmpty) {
      return user[0];
    } else {
      return null;
    }
  }

Error:

Unhandled Exception: type '_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'Iterable'

Second Try:

Future<User> getUserByUid(String uid) async {
    DataSnapshot dataSnapshot =
        await databaseRef.orderByChild("uid").equalTo(uid).once();

    List user = List();

    for (var u in dataSnapshot.value) {
      print(u);
    }

    if (user.isNotEmpty) {
      return user[0];
    } else {
      return null;
    }
  }

Error:

Unhandled Exception: type '_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'Iterable'

For all tries I get the same error. But the .forEach example above works.

Additional question: In .forEach I get also the key variable. Is this also available in Future.forEach in some way?

Upvotes: 0

Views: 1344

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599031

You're trying to loop over a map, but (as the error says) a map isn't iterable. You can loop over the keys of the map though:

for (var key in dataSnapshot.value.keys) {
  print(dataSnapshot.value[key]);
}

Upvotes: 3

Related Questions