gpt4 book ai didi

dart - 从 future 实例中获取值(value)

转载 作者:行者123 更新时间:2023-12-04 09:13:26 25 4
gpt4 key购买 nike

我的数据是这样的:

{
"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;
}
  • 我从数据库(Firebase)访问一个员工(作为Map)
  • 如果员工是领导者(具有关键的“组”)
  • 通过调用一个单独的函数,我从数据库中获得了该组中每个员工的详细信息。
  • 由于该函数返回的映射值为Future的实例,因此我想从中提取实际值。为此,在 map 上调用了forEach
    但是,我仅将Future的实例作为值。

  • 如何获得实际值?

    最佳答案

    无法从异步执行恢复到同步执行。

    要从Future获取值,有两种方法

    将回调传递给then(...)

    theFuture.then((val) {
    print(val);
    });

    或使用 async/ await获得更好的语法
    Future foo() async {
    var val = await theFuture;
    print(val);
    }

    关于dart - 从 future 实例中获取值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46579358/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com