Home > Mobile >  Error with forEach in flutter to show listview with data from firebase realtime
Error with forEach in flutter to show listview with data from firebase realtime

Time:02-21

I am trying to display data in a listview that is in the firebase database realtime, but I am having the forEach problem, what is it really due to? I tried different solutions for a long time but I couldn't fix it, does anyone know what the way to solve this should be?

I attach the code

class UserTask {
Future<List<Task>> getTask() async {
List<Task> groupTask = [];

try {
  DatabaseReference ref = FirebaseDatabase.instance
      .ref()
      .child("grupos")
      .child("grupoid3")
      .child("tareas");

  DatabaseEvent event = await ref.once();

  if (event.snapshot.exists) {
    event.snapshot.value.forEach((key, value) {
      Map mapa = {"key": key, ...value};
      Task nuevaTask = Task(
        titulo: mapa["titulo"],
        contenido: mapa["contenido"],
        key: mapa["key"],
      );
      groupTask.add(nuevaTask);
    });
  }
  return groupTask;
} catch (e) {
  return groupTask;
}

} }

Image error

CodePudding user response:

You need to cast the value so the code knows what to expect and what the object can or cannot do.

Try this:

final tasks = event.snapshot.value as Map<dynamic, dynamic>;

tasks.forEach((key, value) {
  Map mapa = {"key": key, ...value};
  Task nuevaTask = Task(
    titulo: mapa["titulo"],
    contenido: mapa["contenido"],
    key: mapa["key"],
  );
  groupTask.add(nuevaTask);
});
  • Related