Caio Granero
Caio Granero

Reputation: 71

Using firestore with json_serializable after nullsafety

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();
    });
  }
}

Upvotes: 3

Views: 506

Answers (1)

Pham Luc
Pham Luc

Reputation: 1

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>

Upvotes: 0

Related Questions