3

i'm using json_serializable and firestore. json_serializable creates a factory method with Map<String, dynamic> as parameter but after nullsafety changes, firestore start to return a Map<String, dynamic>? as document data and now i can't call json_serializable factory to map my firestore types because show this error message: The argument type 'Map<String, dynamic>?' can't be assigned to the parameter type 'Map<String, dynamic>'

Can someone help me with this? Can't i using json_serializable with firestore anymore?

I wrote this example:

class Entity {
  const Entity({required this.id});

  final String id;

  factory Entity.fromJson(Map<String, dynamic> json) => _$EntityFromJson(json);
  Map<String, dynamic> toJson() => _$EntityToJson(this);
}

class Repository {
  Stream<List<Entity>> list() {
    return FirebaseFirestore.instance.collection('entity').snapshots().map((event) {
      return event.docs.map((e) {
        return Entity.fromJson(
          e.data() // The argument type 'Map<String, dynamic>?' can't be assigned to the parameter type 'Map<String, dynamic>'
        );
      }).toList();
    });
  }
}
  • 1
    The result of the query can be null and you are trying assing to a not null variable, you could make your variable accept null and treat that later or treat the result to check if is null beffore assign to object. – Jorge Vieira Mar 24 '21 at 00:01

1 Answers1

0

I don't know this is a correct way but I use 'as' keyword to convert type from Object to Map<String, dynamic> Image example

doc.data() as Map<String, dynamic>
Pham Luc
  • 1
  • 1