问题
I'm trying to get all the documents inside a determined collection from my firestore and after that, I want to set them in a list of documents which each position of the list represents a document. However, when I made the code, I received this error:
type 'Future' is not a subtype of type 'List' in type cast
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);
}
}
}
回答1:
you need to add await
keyword before the Future
call:
var documents = await loadDocuments() as List;
also, you need to change the return of the loadDocuments()
method like this:
static loadDocuments() async{
var documents = await Firestore.instance.collection('restaurant').getDocuments();
return documents.documents; //this returns a List<DocumentSnapshot>
}
来源:https://stackoverflow.com/questions/57664327/type-futuredynamic-is-not-a-subtype-of-type-listdynamic-in-type-cast