在 Flutter 中从 Firebase 读取数组

str*_*tle 4 dart firebase flutter google-cloud-firestore

我在 Firebase 中定义了一个具有不同字段类型的集合,例如字符串和字符串数组。

我可以DocumentSnapshot简单地通过调用来读取字符串:

String name = document['name'];
Run Code Online (Sandbox Code Playgroud)

但我怎样才能得到List<String>?通过调用

List<String> names1 = document['names'];
List<String> names2 = document['ingredients'].map((x) => x.toString())
Run Code Online (Sandbox Code Playgroud)

我相应地得到以下例外:

“List”类型不是“List”
类型的子类型“MappedListIterable”类型不是“List”类型的子类型

str*_*tle 17

只需使用命名.from构造函数即可完成:

List<String> names = List.from(document['names']);
Run Code Online (Sandbox Code Playgroud)

  • 如果数组当前不存在怎么办 (2认同)
  • 在 DocumentSnapshot 文档上使用此确切代码:类型“String”不是类型“Iterable&lt;dynamic&gt;”的子类型 (2认同)