Home > other >  Flutter - make api call inside Listview
Flutter - make api call inside Listview

Time:05-26

I am calling an api, which will return a list of items (workouts), and items will be shown in a ListView. but I also need to call another api for each item of the ListView to fetch the score of that workout (if there is already a score) and show the score to each workout according to their id. How can I resolve this scenario.? I am using bloc and this is how I am fetching the workouts

Future<void> _onLoadingWod(
      onl oadingWodEvent event, Emitter<WhiteboardState> emit) async {
    emit(state.copyWith(isWodLoading: true));
    final listWods =
        await WhiteboardService().getListWod(state.selectedDay.toString());

    emit(state.copyWith(
        isWodLoading: false, listWods: listWods));
  } 

some workouts may not have a score yet, in that case, I show in the listview a button to log a score for each workout.

I tried something like this:

    final listResults = await Stream.fromIterable(listWods)
        .asyncMap((wod) => WhiteboardService().getresult(wod.id))
        .toList();

but since some workouts may not have result, is showing error.

how can a link workouts with results and show then in a listview? pls any help o guide is appreciated.

CodePudding user response:

As I understand, it can be done from a loop. You have to create a model class for results that include the workout id. Then you can loop through it and find the relevant workout from the workout list and then assign the results for it.

there is an example hope it will help.

*dummy model classes

class Workouts {
  final int id;
  Result? result;

  Workouts({
    required this.id,
    this.result,
  });
}

class Result {
  final int workoutId;
  final String result;

  Result({
    required this.workoutId,
    required this.result,
  });
}

*assign results to workout list

void asignResults() {
    ///for each [results]
    for (Result result in listResults) {
      listWorkouts
          .firstWhere((workout) => workout.id == result.workoutId)
          .result = result;
    }
    listWorkouts.forEach((element) {
      print(element.toString());
    });
  }

I think if you can do this from the backend it will be more efficient than this approach. (eg:- join query in sql)

  • Related