首页 > 解决方案 > 无法在 forEach 循环内的列表中添加元素 - Flutter

问题描述

我有一个追随者列表(模型类),它包含每个用户的 documentId,使用这个 documentId 我可以使用 API 从服务器获取 InstaUser(又是一个模型类)。我在这里要做的是创建一个 InstaUser 列表并返回它。在 forEach 循环内,我将 elememts 插入到列表变量中,但在执行循环后,列表仍然为空。分享下面的功能片段,谁能帮我找到问题。

Future<List<InstaUser>> getMyFollowers() async {
List<InstaUser> list = [];
followerList.forEach((element) async {
  // followerList contains documentId
  String apiUrlForUsers =
      constants().fetchapiUrl + 'details/${element.documentId}.json';
  final currentFollowerResponse = await http.get(Uri.parse(apiUrlForUsers));
  final currentFollowerData =
      json.decode(currentFollowerResponse.body) as Map<String, dynamic>;
  list.add(InstaUser(
    dp: currentFollowerData['dp'],
    userName: currentFollowerData['userName'],
    website: currentFollowerData['website'],
    bio: currentFollowerData['bio'],
    title: currentFollowerData['title'],
    email: currentFollowerData['email'],
    keyIdFromServer: currentFollowerData['keyIdFromServer'],
    uid: currentFollowerData['uid'],
  ));
  print(
      'Current length = ${list.length.toString()} ${currentFollowerData['title']}');
});
print('length = ${list.length}');
return list;}

日志报告:- 正在执行热重新加载...正在将文件同步到设备 sdk gphone x86...在 738 毫秒内重新加载了 1120 个库中的 10 个。I/flutter (19300):长度 = 0 I/flutter (19300):当前长度 = 1 Uzumaki Naruto enter code here I/flutter (19300):当前长度 = 2 Uchiha Sasuke

我也不明白为什么它在任何其他打印语句之前打印长度。

标签: flutterdartasync-awaitflutter-provider

解决方案


推荐阅读