Home > front end >  Flutter/Dart firestore returns LinkedMap - How to use this?
Flutter/Dart firestore returns LinkedMap - How to use this?

Time:10-29

In firestore, I have an array of (simple) maps.

When getting this data into Flutter/Dart, using the cloud_firestore package as follows:

    Stream<T> documentStream<T>({
      required String path,
      required T Function(Map<String, dynamic>? data, String documentID) builder})
      {
        final DocumentReference<Map<String, dynamic>> reference =
            FirebaseFirestore.instance.doc(path);
        final Stream<DocumentSnapshot<Map<String, dynamic>>> snapshots =
            reference.snapshots();
        return snapshots.map((snapshot) => builder(snapshot.data(), snapshot.id));
      }

and consuming this e.g. as follows:

documentStream(
  path: 'firestore_path_doc',
  builder: (data, documentId) {
    final x = data['array_of_maps'];
    print(x[0].runtimeType); // gives LinkedMap<String, dynamic>
    final y = x as List<Map<String, String>>; // fails
    final y1 = x[0] as Map<String, String>; // fails
  },
);

fails.

I cannot find a way to convert the map inside this array to a normal map. In fact, I can barely find any info on LinkedMap. After digging, I see its in the js (https://pub.dev/packages/js) package, but it's internal there, not supposed to be exposed.

If I had a map in firestore, it converts easily to a Map<String, String> in dart. But a map inside an array arrives as a LinkedMap.

How can I work this LinkedMap? I cannot even iterate over it, since it is not recognised at compile time, even if I try to import js.

thx

CodePudding user response:

x[0] type is Map<String, dynamic>. You're trying to cast it to Map<String, String>, which would obviously fail. You can do that manually though:

final x = data['array_of_maps'] as List<Map<String, dynamic>>;
final myMap = x[0].map((key, value) => MapEntry(key, value.toString()));

CodePudding user response:

I got it to work following the answer to this: How to convert an array of map in Firestore to a List of map Dart

Basically by using a class for the inner map instead of a generic Map.

  • Related