method ‘[]’ can’t be unconditionally invoked because the receiver can be ‘null’ with Firestore

If you are working with null safety in Dart and Flutter then I recommend checking this documentation out which explains various small fixes if you have problems working with null values and null safety. Usually you can just simply use the exclamation mark just before a property to check any other value if it also can be null like this:

int f(String? x) { return x!.length; }

But in one situation I couldn’t simply just add the exclamation mark to my property when working with Firestore inside a map function when looping through the Snapshot document Data(). The error I got (see image below) was:

Error: The method ‘[]’ can’t be unconditionally invoked because the receiver can be ‘null’.
Try making the call conditional (using ‘?.’) or adding a null check to the target (‘!’).dart unchecked_use_of_nullable_value

The solution I searched for at the linked page didn’t solve my issue, so what I ended up doing was casting the object type. Let’s say you have a map function for your Firestore CollectionReference like this:

        final mySnapStream = messagesCollection
        .orderBy('date', descending: true)
        .limit(100)
        .snapshots()
        .map((obj) => obj.docs
            .map((e) => new MyItem(
                e.data()['myFieldOne'],
                e.data()['myFieldThree'],
                e.data()['myFieldFour']))
            .toList());
method '[]' can't be unconditionally invoked because the receiver can be 'null'

Then you can simply cast these values with dynamic like so:

      final mySnapStream = messagesCollection
        .orderBy('date', descending: true)
        .limit(100)
        .snapshots()
        .map((obj) => obj.docs
            .map((e) => new MyItem(
                (e.data() as dynamic)['myFieldOne'],
                (e.data() as dynamic)['myFieldThree'],
                (e.data() as dynamic)['myFieldFour']))
            .toList());
method '[]' can't be unconditionally invoked because the receiver can be 'null' fixed

This way we don’t have any errors any longer. The MyItem class was not defined here so please ignore that. Obivously there are probably better ways to go about this, but this is one way.

5 7 votes
Article rating
Subscribe
Notify of
guest
10 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Andre
Article rating :
     

thank you 🙂 helped all the way

Asif Imtiaz Ahmed
Article rating :
     

Thank YOU! that solved it!

Ronak Prajapati

Thank you It helped a lot

Adam Baraja
Article rating :
     

Thank you so much.. very helpful

Kalimwenjuma

Thank you it did help me

Fabio
Article rating :
     

thannkssssss!!!!!!!!!!!!!!

aongid
Article rating :
     

Thank you so much!

Stevenson

Thank you for your helping !

Deepak Neelakandan
Article rating :
     

Thanks it helped a lot

mbsx2
Article rating :
     

thank you 🙂