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:
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.
You can do it this way:
void updatePuppy(Puppy newPuppy){
    
    final oldListOfPuppies = state.listOfPuppies;
    final indexNewPuppy = state.listOfPuppies.indexOf(newPuppy);
    
    oldListOfPuppies[indexNewPuppy] = newPuppy;
    
    state = state.copyWith(
    newListOfPuppies: oldListOfPuppies
    );
  }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With