【问题标题】:Flutter/Dart firestore returns LinkedMap - How to use this?Flutter/Dart firestore 返回 LinkedMap - 如何使用它?
【发布时间】:2021-10-28 16:03:45
【问题描述】:

firestore 中,我有一个array (简单)maps。

当将此数据放入Flutter/Dart 时,使用cloud_firestore 包如下:

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

并消费这个,例如如下:

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

失败。

我找不到将这个数组中的贴图转换为法线贴图的方法。 事实上,我在LinkedMap 上几乎找不到任何信息。挖掘后,我在js (https://pub.dev/packages/js) 包中看到了它,但它是内部的,不应该暴露的。

如果我在firestore 中有一个map,它很容易转换为dart 中的Map&lt;String, String&gt;。但是array 中的mapLinkedMap 的形式出现。

我该如何处理这个LinkedMap?我什至无法对其进行迭代,因为它在编译时无法识别,即使我尝试导入 js

谢谢

【问题讨论】:

  • final y1 = x[0] as Map&lt;String, dynamic&gt; 适合你吗?
  • 您可能找不到任何信息,因为您记错了实际类型,几乎可以肯定是LinkedHashMapLinkedHashMaps 已经是Maps,但您的问题实际上是类型参数不匹配。使用 Map.fromMap.castFrom 将一种 Map 类型转换为另一种具有不同键/值类型的类型。
  • @jamesdlin VS 调试器字面上显示 'LinkedMap' 这是 js 包中的内部类型
  • @AndreyGordeev 不,这也不起作用。同样的错误。 x[0].runtimeType 显示为 LinkedMap&lt;String, dynamic&gt;x[0] as Map&lt;String, dynamic&gt; 失败

标签: flutter dart google-cloud-firestore


【解决方案1】:

我得到了这个答案:How to convert an array of map in Firestore to a List of map Dart

基本上使用class 来表示内部map,而不是通用Map

【讨论】:

    【解决方案2】:

    x[0] 类型为Map&lt;String, dynamic&gt;。您正在尝试将其转换为Map&lt;String, String&gt;,这显然会失败。 您可以手动执行此操作:

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

    【讨论】:

    • 不,这也不起作用。同样的错误。 x[0].runtimeType 显示为 LinkedMap&lt;String, dynamic&gt;x[0] as Map&lt;String, dynamic&gt; 失败
    猜你喜欢
    • 1970-01-01
    • 2019-06-12
    • 2020-05-10
    • 2020-10-22
    • 2022-01-23
    • 2020-01-05
    • 1970-01-01
    • 2019-10-01
    • 2021-05-30
    相关资源
    最近更新 更多