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());
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());
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.
Latest Comments