Let’s say I have a data class Dog that includes a List of puppies.
@immutable
class Dog extends Equatable{
final int id;
final List<Puppy> listOfPuppies;
Dog({required this.id,required this.listOfPuppies});
Dog copyWith({int? newId, List<Puppy>? newListOfPuppies}){
return Dog(id: newId ?? id, listOfPuppies: newListOfPuppies ?? listOfPuppies);
}
@override
List<Object?> get props => [id, listOfPuppies];
}
@immutable
class Puppy extends Equatable{
final String name;
final int age;
Puppy({required this.name, required this.age});
Puppy copyWith({int? newAge, String? newName}){
return Puppy(age: newAge?? age, name: newName ?? name);
}
@override
List<Object?> get props => [name, age];
}
And later down the line I need to update one of the puppies inside the dog class without:
- Changing the order of the listOfPuppies variable provided using Riverpod (important)
- Affecting the other puppies and possibly re-creating them unnecessarily (not important)
For reference I’m using Riverpod and providing the dog anywhere in the app. This is the controller class:
class DogController extends StateNotifier<Dog>{
DogController(super.state);
void updatePuppy(Puppy newPuppy){
//update specific puppy here inside the listOfPuppies list
//state = state.copyWith(listOfPuppies: );
}
}
I’m clueless on how I need to update the puppy using the constraints given above.
2
Answers
My case was a bit more tedious, but with the given instructions from Ruble I was able to update everything smoothly. In my case there was only one more model that was including the Dog class.
Owner model:
Dog model:
And finally the Puppy model was as following:
To update the isVaccinated field inside one of the Puppy models I had to follow these steps inside the controller class:
This way old puppies and dogs were not moved inside the list and only the relevant puppy's isVaccinated field was updated.
You can do it this way: