简体   繁体   English

Flutter Firestore 如何将数组从 firestore 加载到列表

[英]Flutter Firestore How to load array from firestore to a list

I want to load the array from Firestore into a list in Flutter. I tried to use List.castFrom to convert Firestore array into List, but it does not work.我想将 Firestore 中的数组加载到 Flutter 中的列表中。我尝试使用 List.castFrom 将 Firestore 数组转换为 List,但它不起作用。

DocumentReference userDocRef = Firestore.instance.collection('users').document(id);
DocumentSnapshot userDocSnapshot = await userDocRef.get();

List groups = await List.castFrom(userDocSnapshot.data['groups']);

it shows an error: Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List'它显示错误:未处理的异常:类型 '_InternalLinkedHashMap<String, dynamic>' 不是类型 'List' 的子类型

This is the array in my Firestore:这是我的 Firestore 中的数组: 在此处输入图像描述

What should I do?我应该怎么办?

You cannot directly turn a Map into a List.你不能直接把一个 Map 变成一个 List。 You would have to get to use forEach to split the map's key and values.您将不得不使用 forEach 来拆分地图的键和值。 Here is how you can get the Map's values and turn it into a List:以下是获取 Map 的值并将其转换为 List 的方法:

FirebaseDatabase.instance
    .reference()
    .child("users/$id")
    .once()
    .then((snapshot) {
  if (snapshot.value != null) {
    snapshot.value.forEach((k, v) {
      myList.add(v);
    });
  } else {
    print("value is null");
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM