Search code examples
flutterfirebasegoogle-cloud-firestore

How can I deserialize map from Firebase Firestore?


My FirebaseFirestore looks like the below image

Firestore Image

My code snipped for deserialization is as below:

class StripeProductPlan extends Equatable {
  final DocumentReference selfRef;

  final Map<String, String> metaData;
  final String name;
  final String? role;
  final String? taxCode;

  const StripeProductPlan({
    required this.selfRef,
    required this.metaData,
    required this.name,
    this.role,
    this.taxCode,
  });

 factory StripeProductPlan.fromSnapshot(
      DocumentSnapshot<Map<String, dynamic>> snapshot) {
    final data = snapshot.data()!;
    return StripeProductPlan(
      metaData: data['metadata'] as Map<String, String>, //Edited
      selfRef: snapshot.reference,
      name: data['name'] as String,
      role: data['role'] as String? ?? '',
      taxCode: data['taxCode'] as String? ?? '',
    );
  }

Everything else works, except for the metaData deserialization. How do I fix this?


Solution

  • I see in your screenshot:

    enter image description here

    That your Map field is called medatadata while in your class is called metaData, which is not correct. The field names must match. See the difference, the field in the database starts with a lowercase letter d while in the class starts with the capital letter D.

    To solve thisin the simplest way possible, please change the name of the field in the class to match the one in the database:

    class StripeProductPlan extends Equatable {
      final DocumentReference selfRef;
    
      final Map<String, String> metadata; //👈
      final String name;
      final String? role;
      final String? taxCode;
    
      //...
    
    }