0

I am trying to map a firestore document snapshot to a custom object that I have made but am getting this error upon doing so:

E/flutter ( 6555): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: type '(dynamic) => TestMap' is not a subtype of type '(String, dynamic) => MapEntry<dynamic, dynamic>' of 'transform'

From my understanding it has something to do with the way that I am parsing the nested map 'testMap'. Can any Flutter/Firebase/Dart experts out there help me understand what I am doing wrong and how to fix this.

So my data within Firestore looks like this:

enter image description here

The two class objects to parse this data into a usable object like this:

class Categories {
  final String category;
  final String imageurl;
  List testMap = [];

  Categories(this.category, this.imageurl);
  Map<String, dynamic> toMap() => {
        "category": this.category,
        "imageurl": this.imageurl,
        "testMap": this.testMap
      };

  Categories.fromMap(Map<String, dynamic> map)
      : category = map["category"],
        imageurl = map["imageurl"],
        testMap = map["testMap"].map((map) {  // THE ERROR IS HERE (map) 
          return TestMap.fromMap(map);
        }).toList();
}

class TestMap {
  final String v1;
  final String v2;

  TestMap(this.v1, this.v2);

  Map<String, dynamic> toMap() => {
        "v1": this.v1,
        "v2": this.v2,
      };

  TestMap.fromMap(Map<dynamic, dynamic> map)
      : v1 = map["v1"],
        v2 = map["v2"];
}

Finally I get the data from Firestore like this:

  fromFirestore() {

  final FirebaseAuth auth = FirebaseAuth.instance;

  Categories categoryObject;

  CollectionReference categoriesCollection =
      FirebaseFirestore.instance.collection('categories');

  categoriesCollection.doc('categories').get()
      // ignore: missing_return
      .then((docSnapshot) {
    for (var i = 1; i <= docSnapshot.data().length; i++) {
      print(docSnapshot.data()[i.toString()]['testMap'].toString());

      categoryObject = Categories.fromMap(docSnapshot.data()[i.toString()]);
    }
  });
}

I know that firestore maps to Map<String, dynamic> but the error seems to want this subtype of type '(String, dynamic)' instead of Map<String, dynamic> ... perhaps something to do with how my classes are parsing the maps?

Thanks a lot!

1 Answer 1

1

You might need to cast to TestMap

 testMap = map["testMap"].map((map) {  // THE ERROR IS HERE (map) 
          return TestMap.fromMap(map);
        }).toList().cast<TestMap>;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.