如何将Bloc监听加载的每个用户资料添加至指定列表?
问题描述
我有一个名为followSubscribtion的StreamSubscription字段,它监听新关注者事件,然后调用populateFollows加载关注者资料。当前代码运行正常,但希望将每个加载完成的用户资料添加至指定列表,该如何调整?
现有代码如下:
监听与加载触发代码
followsSubscription = getBloc(context).followsHandler.stream.listen((value) async { if (value.status == Status.success) { await populateFollows(); } }); }); populateFollows() async{ if (getBloc(context).followsModel.length > 0) { for (var i = 0; i < getBloc(context).followsModel.length; i++) { getBloc(context).loadFollowsProfile(getBloc(context).followsModel[i].userId); break; // 此处break会导致仅处理第一个关注者 } } }
loadFollowsProfile方法代码
loadFollowsProfile(int id , List<UserProfileModel> profileList) { getFollowsProfileHandler.addNetworkTransformerStream( Network.getInstance().getUserProfile(id), (_) { userProfileModelBloc = UserProfileModel.fromJson(_); profileList.add(userProfileModelBloc); return userProfileModelBloc; }); }
调整方案
需要做两处核心修改,确保所有关注者资料都能被加载并添加到指定列表:
- 修正
populateFollows的循环逻辑:移除break语句以遍历全部关注者,同时传入用于存储资料的目标列表。 - 明确目标列表的作用域:可以将列表定义为类成员变量,或在监听回调内初始化,保证每次加载都能正确收集结果。
修改后的完整代码示例
// 定义存储用户资料的列表(可作为类成员变量,或在需要时初始化) List<UserProfileModel> _followerProfiles = []; followsSubscription = getBloc(context).followsHandler.stream.listen((value) async { if (value.status == Status.success) { // 可选:每次加载新数据前清空列表,避免重复数据 _followerProfiles.clear(); await populateFollows(_followerProfiles); } }); }); populateFollows(List<UserProfileModel> targetList) async { var bloc = getBloc(context); if (bloc.followsModel.isNotEmpty) { // 遍历所有关注者,移除break for (var follow in bloc.followsModel) { bloc.loadFollowsProfile(follow.userId, targetList); } } }
进阶优化(等待所有加载完成)
如果需要等待所有关注者资料加载完成后再执行后续操作,可以将loadFollowsProfile改为返回Future,并使用Future.wait批量等待:
// 修改loadFollowsProfile返回Future Future<UserProfileModel> loadFollowsProfile(int id, List<UserProfileModel> profileList) { Completer<UserProfileModel> completer = Completer(); getFollowsProfileHandler.addNetworkTransformerStream( Network.getInstance().getUserProfile(id), (_) { UserProfileModel model = UserProfileModel.fromJson(_); profileList.add(model); completer.complete(model); return model; }); return completer.future; } // 修改populateFollows等待所有请求完成 populateFollows(List<UserProfileModel> targetList) async { var bloc = getBloc(context); if (bloc.followsModel.isNotEmpty) { List<Future> loadFutures = []; for (var follow in bloc.followsModel) { loadFutures.add(bloc.loadFollowsProfile(follow.userId, targetList)); } await Future.wait(loadFutures); // 所有资料加载完成后,可在此执行后续逻辑 } }
内容的提问来源于stack exchange,提问作者Alex Maina
相关产品推荐
相关产品推荐

