【问题标题】:type 'Future<dynamic>' is not a subtype of type 'List<dynamic>' in type cast类型“Future<dynamic>”不是类型转换中“List<dynamic>”类型的子类型
【发布时间】:2019-12-31 00:34:36
【问题描述】:

我正在尝试从我的 Firestore 中获取已确定集合中的所有文档,然后,我想将它们设置在文档列表中,列表的每个位置都代表一个文档。但是,当我编写代码时,我收到了这个错误:

类型“Future”不是类型转换中“List”类型的子类型

import 'package:cloud_firestore/cloud_firestore.dart';

class Restaurant{

  String keyword;
  String state;
  String address;
  String city;
  int evaluation;
  String image;
  String phone;
  double rating;
  String schedule;
  String text;
  String title;

  Restaurant({
    this.keyword,
    this.state,
    this.address,
    this.city,
    this.evaluation,
    this.image,
    this.phone,
    this.rating,
    this.schedule,
    this.text,
    this.title
  });

  factory Restaurant.fromDatabase(DocumentSnapshot document){
    return Restaurant(
      keyword: document["keyword"] as String,
      state: document["state"] as String,
      address: document["address"] as String,
      city: document["city"] as String,
      evaluation: document["evaluation"],
      image: document["image"] as String,
      phone: document["phone"] as String,
      rating: document["rating"],
      schedule: document["schedule"] as String,
      text: document["text"] as String,
      title: document["title"] as String
    );
  }
}
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:cruke_app/restaurant.dart';

class RestaurantsViewModel {
  static List<Restaurant> restaurants;
  static List<DocumentSnapshot> allDocuments;

  static loadDocuments() async{
    var documents = await Firestore.instance.collection('restaurant').getDocuments();
    return documents;
  } 

  static Future loadRestaurants() async {
    try {

      restaurants = new List<Restaurant>();
      allDocuments = new List<DocumentSnapshot>();

      var documents = loadDocuments() as List;
      documents.forEach((dynamic snapshot) {
        allDocuments.add(snapshot);
      });

      for(int i=0; i < allDocuments.length; i++){
        restaurants.add(new Restaurant.fromDatabase(allDocuments[i]));
      }
    } catch (e) {
      print(e);
    }
  }
}

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    您需要在Future 调用之前添加await 关键字:

    var documents = await loadDocuments() as List;
    

    另外,您需要像这样更改loadDocuments() 方法的返回:

      static loadDocuments() async{
        var documents = await   Firestore.instance.collection('restaurant').getDocuments();
        return documents.documents; //this returns a List<DocumentSnapshot>
      } 
    

    【讨论】:

    • 我这样做了,结果是:type 'QuerySnapshot' is not a subtype of type 'List' in type cast
    • @RafaelCanuto 我已经为答案添加了进一步的修复。
    猜你喜欢
    • 2021-10-20
    • 2021-08-13
    • 2020-09-10
    • 2020-09-20
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 2021-10-23
    • 2020-12-21
    相关资源
    最近更新 更多