我的数据是这样的:

{
  "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;
   }
  1. 我从数据库(Firebase)访问一名员工(作为aMap)
  2. 如果员工是领导者(有一个关键的"组")
  3. 我通过调用一个单独的函数从数据库中获取组中每个员工的详细信息.
  4. 由于函数返回的映射值是Future的实例,因此我想从中提取实际值.为此, map 上称为forEach.

如何获得实际值?

推荐答案

无法从异步执行返回到同步执行.

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

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

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

或使用async/await以获得更好的语法

Future foo() async {
  var val = await theFuture;
  print(val);
}

Dart相关问答推荐

Dart 3.3接口字段类型升级不起作用

Dart 可空记录与模式匹配:(String, int)?类型的匹配值无法分配给所需类型(Object?, Object?)

为什么使用三元条件运算符会产生return_of_invalid_type错误?

`异步内联方法`的这些定义之间有什么区别?

如何在 Flutter 的 firebase_database 中执行事务?

在Flutter中在 initstate() 之前调用了dependOnInheritedElement()

在 Dart 的 Cloud Firestore 中添加文档后如何获取文档 ID

Flutter ButtonRow 填充

结合freezed和hive

自定义声音推送通知不起作用

IndexedDB访问速度和效率

更改底片的灰色覆盖背景

我如何在屏幕上弹出特定的Flutter

如何解决Id does not exist错误?

错误:无法调用需要 const 表达式的非const构造函数

如何为 macos 桌面应用启用 Flutter 上网权限?

Flutter – 连续两个文本,左边一个溢出

可选参数的默认值

包裹构造函数参数的花括号代表什么?

何时在 Dart 中使用 part/part of 与 import/export?