Home > Mobile >  How to get data from the firebase and store it into a list for futher manipulation in dart
How to get data from the firebase and store it into a list for futher manipulation in dart

Time:12-27

List<DocumentSnapshot> docs = snapshot.data.docs;
_selectedSubjects = docs
    .map(
      (doc) => Subject(
        doc['SubjectName'].data(),
        doc['courseIcon'].data(),
        doc['courseCode'].data(),
      ),
    )
    .toList();

I have a class called subject that has attributes/members courseCode, courseIcon, and lastly subjectName. Everything is okay so far, but vs code is saying:

Type: dynamic

The property 'docs' can't be unconditionally accessed because the receiver can be 'null'. Try making the access conditional (using '?.') or adding a null check to the target ('!')."

I have already imported all the necessary libraries, as well as vs code's reccomendations. What should I try?

CodePudding user response:

The error means that snapshot.data may be null, so you need to first verify that it's not null before you can assign it to your non-nullable docs variable:

var querySnapshot = snapshot.data;
if (querySnapshot != null) {
    List<DocumentSnapshot> docs = querySnapshot.docs;
    _selectedSubjects = docs
        .map(
          (doc) => Subject(
            doc['SubjectName'],
            doc['courseIcon'],
            doc['courseCode'],
          ),
        )
        .toList();
}

The local querySnapshot variable is guaranteed to be non-null inside the if block, so now you can simply assign querySnapshot.docs to docs.

I also removed the .data() calls, as @Gwhyyy pointed out in their comment.

You might want to take a moment to read up on nullability in Dart as you're likely to encounter many more situations where the type changes based on handling null.

  • Related