我具有执行某些firestore
操作并检索数据的功能。
但是问题是这将返回一个空值。我发现的原因是,它在获取数据之前会返回值,它不会等到它检索到数据。
这是我的代码。我已经打印了一些print
语句来检查执行顺序。
getNewsOnSearchBar() {
final String _collection = 'news';
final Firestore _fireStore = Firestore.instance;
var newsList = [];
print("1");
getData() async {
print("2");
return await _fireStore.collection(_collection).getDocuments();
}
getData().then((val) async{
if (val.documents.length > 0) {
print("3");
for (int i = 0; i < val.documents.length; i++) {
newsList.add(await val.documents[i].data["headline"]);
}
} else {
print("Not Found");
}
});
print("4");
return ok;
}
输出为:
I/flutter (17145): 1
I/flutter (17145): 2
I/flutter (17145): 4 // 4 prints before 3
I/flutter (17145): 3
我需要的输出是:
I/flutter (17145): 1
I/flutter (17145): 2
I/flutter (17145): 3
I/flutter (17145): 4
有人可以帮我吗?
答案 0 :(得分:1)
当您要等待Future
中的值时,不要使用then
,而要使用await
:
Future<int> myFunc() {
return Future.delayed(Duration(seconds: 1), () => 0);
}
void main() async {
final int result = await myFunc();
print(result);//0
}
对于您来说,您想做类似的事情(可以根据需要进行更改):
getNewsOnSearchBar() async {
final String _collection = 'news';
final Firestore _fireStore = Firestore.instance;
var newsList = [];
print("1");
getData() async {
print("2");
return await _fireStore.collection(_collection).getDocuments();
}
final ref = await getData();
if (ref.documents.length > 0) {
print("3");
for (int i = 0; i < ref.documents.length; i++) {
newsList.add(await ref.documents[i].data["headline"]);
}
} else {
print("Not Found");
}
print("4");
return ok;
}
答案 1 :(得分:1)
您可以使用await代替使用,这应该可以解决您的问题。 这是代码更改后的外观,我强烈建议您指定函数将返回的数据类型。
getNewsOnSearchBar() async {
final String _collection = 'news';
final Firestore _fireStore = Firestore.instance;
var newsList = [];
print("1");
Future<QuerySnapshot> getData() async {
print("2");
return await _fireStore.collection(_collection).getDocuments();
}
QuerySnapshot val = await getData();
if (val.documents.length > 0) {
print("3");
for (int i = 0; i < val.documents.length; i++) {
newsList.add(val.documents[i].data["headline"]);
}
} else {
print("Not Found");
}
print("4");
return ok;
}