我的数据是这样的:
{
"five": {
"group": {
"one": {
"order": 2
},
"six": {
"order": 1
}
},
"name": "Filbert",
"skill": "databases"
},
"four": {
"group": {
"three": {
"order": 2
},
"two": {
"order": 1
}
},
"name": "Robert",
"skill": "big data"
},
"one": {
"name": "Bert",
"skill": "data analysis"
},
"seven": {
"name": "Colbert",
"skill": "data fudging"
},
"six": {
"name": "Ebert",
"skill": "data loss"
},
"three": {
"name": "Gilbert",
"skill": "small data"
},
"two": {
"name": "Albert",
"skill": "non data"
}
}
我正在使用以下功能:
Future retrieve(String id) async {
Map employeeMap = await employeeById(id); //#1
if (employeeMap.containsKey("group")) { //#2
Map groupMap = employeeMap["group"];
Map groupMapWithDetails = groupMembersWithDetails(groupMap); #3
// above returns a Mamp with keys as expected but values
// are Future instances.
// To extract values, the following function is
// used with forEach on the map
futureToVal(key, value) async { // #4
groupMapWithDetails[key] = await value;
}
groupMapWithDetails.forEach(futureToVal); // #4
}
return groupMapWithDetails;
}
Map
从数据库(Firebase)访问一名员工(作为)Future
,因此我想从中提取实际值。为此forEach
,在地图上称为a 。但是,我仅将Future的实例作为值。如何获得实际值?
无法从异步执行恢复到同步执行。
从a获得价值Future
有两种方法
将回调传递给 then(...)
theFuture.then((val) {
print(val);
});
或使用async
/await
以获得更好的语法
Future foo() async {
var val = await theFuture;
print(val);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句