List nums = [1, 2, 3];
print(nums[10] ?? nums[0]);
Unhandled exception: RangeError (index): Invalid value: Not in inclusive range 0..2: 10
The []
operator on List
are not nullable. So it does not return null
if you are asking for an element not in the List
. Instead, it documents a requirement that the given index must be in the List
:
The index must be a valid index of this list, which means that index must be non-negative and less than length.
https://api.dart.dev/stable/2.17.6/dart-core/List/operator_get.html
This is different from the []
operator on Map
which does return null
in case the asked element does not exist in the Map
.
A reason for this design choice would be that it would get really annoying if we should always handle potential null values when asking for elements in lists. Especially since we often do iterate the list where we take the length into account.
Compared to Map
where we are more likely to use it as some form of cache.