Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update value of variable inside list inside data class using Riverpod and copyWith method

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:

  1. Changing the order of the listOfPuppies variable provided using Riverpod (important)
  2. 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.

like image 559
bqubique Avatar asked Sep 15 '25 18:09

bqubique


1 Answers

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
    );
  }
like image 100
Ruble Avatar answered Sep 17 '25 08:09

Ruble