Dart program to change single or multiple list item:
In this post, we will learn how to change one single element or multiple items of a list. Using the index, we can change any specific value of the list or we can change multiple items in the list in a range.
Updating one item using the index:
We can update any specific item in a list by using its index. We can access any item in a list by using the index and also, similarly, we can change the value at that index. For example:
void main() {
List givenList = [1, 2, 3, 4, 5];
givenList[0] = -1;
print(givenList);
}
It will print:
[-1, 2, 3, 4, 5]
Here, we are changing the value of the first element or element at index 0 using the index. We are changing the value to -1.
Changing multiple items using replaceRange:
replaceRange is another method that can be used to replace all items in a range using a different iterable objects.
It is defined as below:
List.replaceRange(int start, int end, Iterable items)
Here,
start - It is the start index from where we want the replacement to start
end - It is the stop index for the replacement
items - An iterable objects those we are replacing
Let’s take a look at the below example:
void main() {
List givenList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
List replace = [11, 12, 13, 14];
givenList.replaceRange(0, 4, replace);
print(givenList);
}
Here, we are replacing all elements of givenList in index range 0 to 4 with the second list replace.
It prints the below output:
[11, 12, 13, 14, 5, 6, 7, 8, 9, 10]
replaceRange if range is larger than the replacing iterable:
If the range in which we are replacing the items is less than the replacing objects, it will truncate the list.
For example:
void main() {
List givenList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
List replace = [11, 12, 13, 14];
givenList.replaceRange(0, 9, replace);
print(givenList);
}
It will print the below output:
[11, 12, 13, 14, 10]
replaceRange for invalid range:
It throws one RangeError for invalid range values. If I use the below range:
givenList.replaceRange(0, 29, replace);
It will throw an error like below: