void main() {
//First Method - update
List myList = [1, 2, 3];
myList[0] = 123;
print(myList);
//Second Method - using .replaceRange() method
var myList2 = [10, 20, 30, 40, 50];
myList2.replaceRange(0, 3, [11, 21]);
print(myList2);
}
If you want to change a single item value with another item value, then you can use the index of that item and assign a new value to it by using the below syntax.
list[index] = newValue
For example, if there is a list of fruits that contains names of the fruits. And you want to change the name Mango to Orange using its index then you can use the below code for that
void main() {
List<String> fruits = ["Apple", "Mango", "Banana"];
fruits[1] = "Orange"; // The index of Mango is 1
print(fruits);
}
Output
[Apple, Orange, Banana]
You can replace many items with another item using the .replaceRange() method of the dart. You need to provide startIndex, endIndex, and a new list that contains items that need to be updated in the list.
The basic syntax
.replaceRange(startIndex, endIndex, [])
In the below example we are replacing items start from 0 indexes to 2 with new values.
void main() {
List<String> fruits = ["Apple", "Mango", "Banana", "Orange", "Grapes"];
fruits.replaceRange(0, 3, ["fruit 1", "fruit 2"]);
print(fruits);
}
0 Comments