Listen to a new value of a bloc and generate a list of listened items

Viewed 24

I have this StreamSubscription field called followSubscribtion. It listens if there is a new follower and then calls populateFollower to load follower profile.

   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;
        }
    }
  }

This works fine, But I want each profile that will be loaded to be added to a list, How do I do that?

loadFollowsProfile method

  loadFollowsProfile(int id , List<UserProfileModel> profileList) {
    getFollowsProfileHandler.addNetworkTransformerStream(
        Network.getInstance().getUserProfile(id), (_) {
      userProfileModelBloc = UserProfileModel.fromJson(_);

      profileList.add(userProfileModelBloc);

      return userProfileModelBloc;
    });
  }
1 Answers

You can do this by setting up loadFollowsProfile() to return a UserProfileModel, adding that to a list in the for loop of populateFollows(), and then returning that list from populateFollows().

List<ProfileObject> populateFollows() async{
      List<ProfileObject> profileList = [];
      if (getBloc(context).followsModel.length > 0) {
        for (var i = 0; i < getBloc(context).followsModel.length; i++){
          profileList.add(getBloc(context).loadFollowsProfile(
              getBloc(context).followsModel[i].userId
          ));
          break;
        }
    }
    return profileList;
  }

followsSubscription =
          getBloc(context).followsHandler.stream.listen((value) async {
        if (value.status == Status.success) {
          profileList = await populateFollows();
        }
      });
    });
Related