Search code examples
flutterdartflutter-riverpod

How to replace a selected item in flutter riverpod


I have a list where i add items using riverpod. I wanted to replace an item in the already selected list.

What i have tried:

class SelectItemNotifier extends StateNotifier<List<SelectedMedia>> {
  SelectItemNotifier() : super([]);

  
 void addItem()  {
      state = [...state, SelectedMedia(
        file: file
        duration: duration,
        id: id,
        type: type,
        videoDuration: videoDuration
      ),
     ];
   }

  void replaceList(int index, SelectedMedia futureFile) {  
     state.replaceRange(index, index + 1, [futureFile]);
  }


}

In normal way, I can easily do

void replaceList(int index, List newList) {  
         lists.replaceRange(index, index + 1, [newList]);
      }

But doesn't work with riverpod.


Solution

  • It should be something like

    if states are immutable Create a local temp variable like

    var temp =List<YOUR_LIST_TYPE>.of(state);
    state =  temp.replaceRange(index, index + 1, [newList]);