在Flutter中等待异步

时间:2020-04-15 08:54:26

标签: flutter asynchronous dart future

我正在尝试用Flutter编写Matrix服务器客户端应用程序。

我从用户所属的服务器请求组。

Future<List> joinedRooms(String accessToken) async {
  String url = server + "/_matrix/client/r0/joined_rooms";
  Map<String, String> headers = {"Authorization": "Bearer $accessToken"};
  Response response = await get(url, headers: headers);
  JoinedRooms roomsID = JoinedRooms.fromJson(jsonDecode(response.body));

  List names = [];

  roomsID.joinedRooms.forEach((roomID) async {
    await roomState(accessToken, roomID).then((value) async {
      await names.add(value[6].content.name);
    });

  return names;
  });

response.body的以下值即将到来

{
  "joined_rooms": [
    "!JSHWMPAgoJdkQvRQrr:example.com",
    "!WzjRnPpUASluIsGTuo: example.com"
  ]
}

使用.forEach方法,我想为每个组ID请求组的名称,并将其添加到names列表中。

Future<List<RoomState>> roomState(String accessToken, String roomID) async {
  String url = server + "/_matrix/client/r0/rooms/$roomID/state";
  Map<String, String> headers = {"Authorization": "Bearer $accessToken"};
  Response response = await get(url, headers: headers);
  List<RoomState> states = (json.decode(response.body) as List).map((i) => RoomState.fromJson(i)).toList();
  return states;
}

names的列表始终为空。 async不在等待代码段。我尝试了很多方法,但没有成功。

1 个答案:

答案 0 :(得分:0)

您没有等待forEach中运行的功能

roomsID.joinedRooms.forEach((roomID) async {
  await ...
});

await不起作用,因为在forEach中没有什么要说的函数等待。 在DartPad

上尝试以下示例
import 'dart:async';

void main() async {

  List<int> list = [1, 2, 3];

  list.forEach((value) async {
    await Future.delayed(Duration(seconds: value));
    print('Waited $value');
  });

  print('Finished main');

}

结果是:

Finished main
Waited 1
Waited 2
Waited 3

因为每个人都不必等待内部的功能。

请尝试:

for(.. in ..) {
    await ...
}