'Flutter; replace item in list
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 :)
Solution 1:[1]
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]
}
Solution 2:[2]
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.
Solution 3:[3]
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.
Solution 4:[4]
First occurrence simplest solution
final l = [1,2,3,4];
l[l.indexOf(2)] = 5;
print(l); // [1,5,3,4]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | xamantra |
Solution 2 | ChristianS |
Solution 3 | marc_s |
Solution 4 | genericUser |