flutter - 无法在 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
我也不明白为什么它在任何其他打印语句之前打印长度。
解决方案
推荐阅读
- tensorflow - Tensorflow 管道,批量预处理:初学者问题
- vb.net - 通过 COM 从 VB6 访问嵌套的 VB.NET 类
- ios - IOS中的领域:插入对象后无法更改主键
- java - Hibernate:在广泛的类层次结构中有效地加载具有祖先类型的对象列表
- reason - 在 ReasonReact 中处理孩子
- spring - SpringBoot - 解析 HTTP 请求标头时出错(Oauth2 https 端点)
- laravel - 从查询中的日期属性获取年份
- ionic-framework - 无法在 IONIC 中的另一个类 app.component.ts 上获取存储变量
- apache-kafka - Kafka Streams:对象创建
- javascript - 如何使用 reactjs 使用相同的输入框存储不同的值?