firebase_database – error after flutter migration – DataSnapshot syntax

Issue

I used this code bevor migration

  void initState() {
    DatabaseReference db;
    db = FirebaseDatabase.instance.ref().child("likes");
    db.once().then((DataSnapshot snapshot) {
      Map<dynamic, dynamic> values = snapshot.value;
      values.forEach((key, values) {
        likeList.add(values["check"]);
        print(likeList);
      });
    });
  }

after "dart pub upgrade –null-safety" I get the Error:

The argument type 'Null Function(DataSnapshot)' can't be assigned to the parameter type 'FutureOr<dynamic> Function(DatabaseEvent)

I can’t find anything in the changelos on pub.dev how to use DataSnapshot in this case.

Solution

Instead of DataSnapshot, you should put DatabaseEvent within the then

  void initState() {
    DatabaseReference db;
    db = FirebaseDatabase.instance.ref().child("likes");
    db.once().then((DatabaseEvent databaseEvent) {
      Map<dynamic, dynamic> values = databaseEvent.snapshot.value;
      values.forEach((key, values) {
        likeList.add(values["check"]);
        print(likeList);
      });
    });
  }

Answered By – Sahil Hariyani

Answer Checked By – Senaida (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *