我正试图从我的Firestore中获取所有文档到确定的集合中,然后,我想将它们设置在文档列表中,该列表的每个位置都代表一个文档。但是,在编写代码时,我收到此错误:
类型'Future'不是强制类型转换中'列表'类型的子类型
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);
}
}
}
答案 0 :(得分:2)
您需要在await
调用之前添加Future
关键字:
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>
}