Dart Program to update or replace List items or values

To update list items of a list collection in dart you can use the index value of the list starts from 0 or the .replaceRange() method.

void main() {
  //First Method - update 
  List myList = [1, 2, 3];
  myList[0] = 123;
  //Second Method - using .replaceRange() method
  var myList2 = [10, 20, 30, 40, 50];
  myList2.replaceRange(0, 3, [11, 21]);

Update list item using index

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


[Apple, Orange, Banana]

Update list items using .replaceRange() method

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"]);
Was this helpful?