We will learn how to update flutter bloc item in the list.
First then you have to know that when you are creating a bloc or cubit using flutter_bloc, you have to create state classes and as you extend bloc or cubit, then you have mention the type of the state class in a List.
class WorkoutsCubit extends Cubit<List<Workout>> { WorkoutsCubit() : super([]); .......................... .......................... }
I am using Cubit in this case. So I did not mention the events in the Cubit<T>
Now in List<Workout> my Workout class is stateful since we extend Equatable class.
class Workout extends Equatable { final String? title; final List<Exercise> exercises; }
So now you get that, Workout classes are saved in List. The list is List<Workout>
Now we will see how to update the list, if we update the Workout class.
Say for example we changed title or exercises fields in the Workout class, then we will do like below in WorkoutsCubit class
Workout newWorkout = Workout(title: workout.title, exercises: []);
int exIndex = 0;
int startTime = 0;
for (var ex in workout.exercises) {
newWorkout.exercises.add(Exercise(
prelude: ex.prelude,
title: ex.title,
duration: ex.duration,
index: exIndex,
startTime: startTime));
exIndex++;
startTime += ex.prelude! + ex.duration!;
}
/*
because we have a list of states we we could do index
*/
state[index] = newWorkout;
print("all data is ${state.length}");
emit([...state]);
You see that we did state[index]= newWorkout and then emit([…state]) does the trick to update the list of List<Workout>
So here since List<Workout> is a list, and we can find all the states in state property , then setting state[index] would update the list with the new value newWorkout.
If we are using Cubit, then we will call the a method. If you are using BLoC you will call the above code inside on<E>() method().
saveWorkout(){
Workout newWorkout = Workout(title: workout.title, exercises: []);
int exIndex = 0;
int startTime = 0;
for (var ex in workout.exercises) {
newWorkout.exercises.add(Exercise(
prelude: ex.prelude,
title: ex.title,
duration: ex.duration,
index: exIndex,
startTime: startTime));
exIndex++;
startTime += ex.prelude! + ex.duration!;
}
/*
because we have a list of states we we could do index
*/
state[index] = newWorkout;
print("all data is ${state.length}");
emit([...state]);
}
The above code uses Cubit to update a List. If you just want BLoC(without the subset Cubit), then you may click on the below link and learn more about updating a List using BLoC.