Dart Programming - Updating Index of a List Element



Updating the index

Dart allows modifying the index of an item in a List. In other words, one can re-write the value of list item. The following example illustrates the same −

Example

void main() { 
   List l = [1, 2, 3]; 
   l[0] = 123; 
   print(l); 
}

Output

The above example updates the value of the List item with index 0. The output of the code will be −

[123, 2, 3]

Using Invalid index

Dart throws error if index is not in inclusive range of list. The following example illustrates the same −

Example

void main() { 
   List l = [1, 2, 3]; 
   l[-1] = 123; 
   print(l); 
}

Output

The above example updates the value of the List item with index 0. The output of the code will be −

Warnings/Errors:
Unhandled exception:
RangeError (index): Invalid value: Not in inclusive range 0..2: -1
#0      List._setIndexed (dart:core-patch/growable_array.dart:274:49)
#1      List.[]= (dart:core-patch/growable_array.dart:269:5)
#2      main (file:///home/cg/root/f3d4e4fe/main.dart:3:5)
#3      _delayEntrypointInvocation. (dart:isolate-patch/isolate_patch.dart:297:19)
#4      _RawReceivePort._handleMessage (dart:isolate-patch/isolate_patch.dart:184:12)
dart_programming_lists_basic_operations.htm
Advertisements