Flutter; replace item in list

Viewed 7695

I have a list in my app. It containe a couple of items.

I want to replace every item that is equal to a user-input(A String) , with another user-input(Another String). (If the solution is to remove the item, and add a new one, it needs to be in the same location in the list)

How do I do that?

Thanks :)

4 Answers

You can also use replaceRange for this:

void main() {
  var list = ['Me', 'You', 'Them'];
  print(list); // [Me, You, Them]
  var selected = 'You'; // user input A (find)
  var newValue = 'Yours'; // user input B (replace)
  
  // find the item you want to replace, in this case, it's the value of `selected`.
  var index = list.indexOf(selected);
  
  // if replacing only one item, the end index should always be `startIndex` +1.
  // `replaceRange` only accepts iterable(list) so `newValue` is inside the array.
  list.replaceRange(index, index + 1, [newValue]);
  
  print(list); // [Me, Yours, Them]
}
for (int i = 0; i < LIST.length; i++){
    if (LIST[i] == USERINPUT1){
        LIST[i] = USERINPUT2;
    }
}

Basically iterate through the list in the app to check if the input is equal to the user's input.

OR

index = LIST.indexOf(USERINPUT1);

if (index != -1){
    LIST[index] = USERINPUT2;
}

This only works for the first occurrence though.

Here is how I would do it:

void main() {
  String inputString = 'myInput'; // User input to replace inside the list
  List<String> list = ['1', inputString, '3', '4', '5', inputString, '7']; // List of items
  List<String> filteredList = list.where((e) => e == inputString).toList();
  for (final e in filteredList) {
    final index = list.indexOf(e);
    list.removeAt(index);
    list.insert(index, 'newInput'); // Replacing inputString by 'newInput'
  }
}

Basically what I'm doing is creating a sublist filteredList containing only the occurrence of the user input. Then I iterate over my filteredList, before removing the item from list I'm keeping its index to insert my new element at the correct position.

Try the code on DartPad

First occurrence simplest solution

final l = [1,2,3,4];
l[l.indexOf(2)] = 5;
print(l); // [1,5,3,4]
Related