Flutter - Check if Index exist in a List

In this code example, we are going to check if a given index exists in a Flutter List or not. We will be using different methods in order to do that.

Check if Index exist in a List

We will be using List.asMap().containsKey(index) to check whether an index exists in a list or not.

The given Flutter code demonstrates how to check if a specific index exists in a list.

List<int> numbers = [1, 2, 3, 4, 5];

//Check if index 6 exists
if (numbers.asMap().containsKey(6)) {
  print('Index exists');
} else {
  print('Index does not exist');


Index does not exist

In the code, a list of integers named "numbers" is declared and initialized with the values [1, 2, 3, 4, 5]. The list contains five elements, and its indices range from 0 to 4.

The code then uses the asMap() method on the "numbers" list. This method returns an Iterable of the list's elements as key-value pairs, where the keys represent the indices, and the values represent the corresponding elements.

The containsKey() method is then called on the result of asMap() with argument 6, which represents the index we want to check for existence. This method checks if the provided key (index) exists in the iterable.

In this case, since the list "numbers" does not have an element at index 6 (indices start from 0), the containsKey() method will return false. Therefore, the code will execute the else block.

The code will print the message "Index does not exist" because the condition numbers.asMap().containsKey(6) evaluates to false.

Basic Syntax

if (List.asMap().containsKey(index)) {
  print('Index exists');
Was this helpful?