Georgios
Georgios

Reputation: 1037

Transforming a Map with the use of Typecasts to save in Firestore

I have a map within my client that I want to save into cloud Firestore.

To do this, I have to map it to a Map<String,dynamic> type otherwise I will be getting errors due to Firestore rules.

I have already written a map method but it is too wordy.

Map<String, dynamic> transformClassAMapToFirestoreMap(
      Map<String, ClassA> myMap) {
    Map<String, dynamic> map = {};
    myMap.forEach((key, value) {
      map[key] = value.toMap();
    });
    return map;
  }

I know that there is a method Map.from() that transforms a map to a map of other type and is a one-liner. Unfortunately, I do not know how to use this in my case.

What I have is a Map<String, ClassA> myMap; and I implement it like this:

Map<String, dynamic> toMap() {
 return {
  'myMap': Map<String, dynamic>.from(myMap);
 }
}

Unfortunately I am getting the following error:

I/flutter ( 7669): Invalid argument: Instance of 'ClassA'
E/flutter ( 7669): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: Invalid argument: Instance of 'ClassA'

Upvotes: 0

Views: 53

Answers (1)

Georgios
Georgios

Reputation: 1037

Here is the answer:

Map<String, Map<String, dynamic>>.from(myMap?.map((key,value) => MapEntry(key, ClassA.toJson())))

and the toJson returns a Map<String, dynamic> in which I serialize all my properties.

Upvotes: 1

Related Questions