Home > Software design >  Trouble Reading Firebase Database Data in Flutter
Trouble Reading Firebase Database Data in Flutter

Time:01-21

I made what I believe were the correct changes, however, now I'm getting an error that says I can't use forEach here because it may return null. I can't force it by using '!' because then I get another error about not being able to because the method 'forEach' isn't defined for the type 'Object'.

void loadStudentList(){
    // function that loads all students from firebase database and display them in list view
    FirebaseDatabase.instance.ref("students").once()
        .then((databaseEvent) {
      print("Successfully loaded the data");
      print(databaseEvent);
      print("Key:");
      print(databaseEvent.snapshot.key);
      print("value:");
      print(databaseEvent.snapshot.value);
      print("Iterating the value map");
      var studentTmpList = [];
      databaseEvent.snapshot.value!.forEach((k, v) {
        print(k);
        print(v);
        studentTmpList.add(v);
      });
      print("Final student list");
      print(studentTmpList);
      studentList = studentTmpList;
      setState(() {

      });
    }).catchError((error) {
      print("Failed to load the data");
      print(error);
    });
  }

CodePudding user response:

What you are naming datasnapshot is actually a databaseEvent and should really be named as such for clarity. The event has a snapshot and the snapshot has a key and a value. So, to get the key you should be able to use datasnapshot.snapshot.key. Similarly, the value will be datasnapshot.snapshot.value.

You really should read this doc... https://firebase.flutter.dev/docs/database/usage/

UPDATE:

Based on the comment below, in your revised code change

databaseEvent.snapshot.value!.forEach((k, v) {...

to

final snapshotValue = databaseEvent.snapshot.value! as Map<dynamic, dynamic>;     
snapshotValue.forEach((k, v) {...
  • Related