Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter; replace item in list

Tags:

list

flutter

dart

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 :)

like image 782
Tobias H. Avatar asked Aug 25 '26 22:08

Tobias H.


2 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]
}
like image 73
xamantra Avatar answered Aug 29 '26 03:08

xamantra


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.

like image 38
ChristianS Avatar answered Aug 29 '26 04:08

ChristianS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!