【问题标题】:error : type 'Future<dynamic>' is not a subtype of type 'List<dynamic>'. Flutter错误:类型“Future<dynamic>”不是“List<dynamic>”类型的子类型。扑
【发布时间】:2022-01-23 07:05:25
【问题描述】:

我使用 firestore 来检索我的数据库作为地图列表,但是当我尝试使用它时说

类型“未来”不是类型“列表”的子类型

它说这是一个未来,我想把它转换成 List

谢谢

CollectionReference _collectionRef =
    FirebaseFirestore.instance.collection('code');

getData() async {
  // Get docs from collection reference
  QuerySnapshot querySnapshot = _collectionRef.get();

  // Get data from docs and convert map to List
  final allData = querySnapshot.docs.map((doc) async => doc.data()).toList();
  print(allData);

  return allData;
}

更新:

这是没有等待/同步的代码:

'
CollectionReference _collectionRef =
    FirebaseFirestore.instance.collection('code');

getData() {
  // Get docs from collection reference
  QuerySnapshot querySnapshot = _collectionRef.get();

  // Get data from docs and convert map to List
  final allData = querySnapshot.docs.map((doc) => doc.data()).toList();
  print(allData);

  return allData;
}'

同样的信息出现:

 `type 'Future<dynamic>' is not a subtype of type 'List<dynamic>`

【问题讨论】:

  • 你不能在 map 中使用异步函数——在这种情况下,它甚至是必要的,因为你只是想调用doc.data()
  • 我只是想把这个函数的返回转换成一个我可以使用的变量
  • 正如@RichardHeap 所说,只需删除不必要的async 关键字querySnapshot.docs.map((doc) =&gt; doc.data()).toList(); 就足够了
  • 还是不行。它说是一种 future
  • ` getData() { // 从集合引用获取文档 QuerySnapshot querySnapshot = _collectionRef.get(); // 从 docs 中获取数据并将 map 转换为 List final allData = querySnapshot.docs.map((doc) => doc.data()).toList();打印(所有数据);返回所有数据; }` 如果我删除异步代码根本不起作用

标签: flutter dart google-cloud-firestore flutter-futurebuilder


【解决方案1】:

你可以试试这个: 将getData() 更改为Future&lt;List&gt; getData()

【讨论】:

    猜你喜欢
    • 2021-08-13
    • 2020-01-07
    • 2020-09-20
    • 2019-12-31
    • 1970-01-01
    • 2021-10-20
    • 1970-01-01
    • 1970-01-01
    • 2021-09-08
    相关资源
    最近更新 更多