skip to Main Content

I’m using a Riverpod NotifierProvider with a List of data objects as the data source.

class FooData {
  final int data1;
  final String data2;
  final String data3;

  FooData({this.data1 = 0, this.data2 = "", this.data3 = "",});

  FooData copyWith({int? data1, String? data2, String? data3,}) {
    return FooData(data1: data1 ?? this.data1, data2: data2 ?? this.data2, data3: data3 ??    this.data3); 
  }

final foodataListProvider = NotifierProvider<FooDataListNotifier, List<FooData>>(FooDataListNotifier.new);

class FooDataListNotifier extends Notifier<List<FooData>> {
  void addFooData(FooData input) {
    state = [...state, input];
  }

  void updateFooAt(int index, {int? data1, String? data2, String? data3}) {
    //This is where I'm not sure what exactly what I need to do to update the state
    //while maintaining the immutability for the list.
    state[index].copyWith(
      data1: data1 ?? state[index].data1,
      data2: data2 ?? state[index].data2, 
      data3: data3 ?? state[index].data3,);
    state = [...state];
  }

}

The addFooData method works as expected but I am unable to update the items in the list with the provider.

In my ConsumerWidget I am accessing it by using final provider = ref.watch(foodataListProvider);
for the provider and final notifier = ref.watch(foodataListProvider.notifier); for the notifier.
Then in an onPressed in a ElevatedButton I access it like this notifier.updateFooAt(index, data1: "New Data");

I have tried different updateFooAt implementations like

FooData data = state[index]; 
data.copyWith(data1: data1); 
state = [...state, data];

and

List<FooData> dataList = state; 
dataList[index].copyWith(data1: data1); 
state = [...dataList];

I’ve also accessed it in the onPressed using ref.read(foodataListProvider.notifier).updateFooAt(index, data1: "New Data");

When I debug I see that there are new FooData’s added to the list but when I try to update them they keep the data from addFooData, they don’t update.

I looked at this solution but it uses a list inside the data object. Not that I’m opposed to that but I’d like to figure out how to do it with my setup. A few other questions have given me ideas but not solved the problem.

2

Answers


  1. Notifier<List<SomeType>> is troublesome. All updates must be accompanied by a call to ref.notifyListeners(). That will solve your immediate problem, but consider using an IList (fast immutable collections) or a custom list-holder class instead to make it immutable.

    Login or Signup to reply.
  2. try using ConsumerStatefulWidget instead of ConsumerWidget

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search