本文介绍了Flutter:在读取Firebase数据时进行异步处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试从Firebase读取数据时进行异步处理,
I try to do sthg asynchronous while reading data from Firebase and it doesn't work,
这是我尝试过的:
Future<String> test() async {
var cacheManager = await CacheManager.getInstance(); //await here is OKAY
DatabaseReference firebaseRef = FirebaseDatabase.instance.reference();
firebaseRef.child('...').once().then((DataSnapshot snapshot) {
Map<dynamic,dynamic> map = snapshot.value;
map.forEach((key, url) {
print('$key: $url'); //OKAY
await precacheImage(new NetworkImage(url), context); //doesn't cache images
});
});
return "";
}
我得到了:
我也尝试过:
Future<Map> test() async { //<---- added type Map
...
map.forEach((key, url) async { //<--- added async
//var file = await cacheManager.getFile(url);
await precacheImage(new NetworkImage(url), context); //same, cache doesn't work
});
但是我得到了:
有什么主意吗?
推荐答案
您将一个函数传递给then(...)
,在该函数中使用await
,为此功能需要标记为async
. br>仅将其他一些外部功能标记为async
是不够的.
You pass a function to then(...)
and in that function you use await
and for that to work the function needs to be marked async
.
It's not sufficient that some other outside function is marked async
.
firebaseRef.child('...').once().then((DataSnapshot snapshot) async { // async here was missing
Map<dynamic,dynamic> map = snapshot.value;
map.forEach((key, url) {
print('$key: $url'); //OKAY
var file = await cacheManager.getFile(url); // doesn't work
});
它可能仍然不起作用,但这取决于您要对file
进行的操作,而您的问题尚不清楚.
It' might still not work but it depends on what you want to do with file
and that's not clear from your question.
这篇关于Flutter:在读取Firebase数据时进行异步处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!