Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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 (‘!’)."

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading