Unhandled Exception: Type ‘String’ is not a subtype of type ‘int’ of ‘index’
This error occurs when you try to access an element in a list or an item of an array using an index, but instead of providing an integer value as the index, you provide a string. The error message indicates that the provided string cannot be treated as an integer index.
To understand this error better, let’s look at some examples:
Example 1:
In this example, we have a list of numbers and we mistakenly use a string as an index to access an item:
List<int> numbers = [1, 2, 3, 4, 5];
String index = "2";
print(numbers[index]); // Throws the 'String is not a subtype of int' error
In this case, the variable index
is a string with the value “2”. However, when trying to access the item at index “2” in the numbers
list, the error occurs because the index should be an integer, not a string.
Example 2:
In this example, we have an array and mistakenly pass a string to access an element:
var array = [1, 2, 3, 4, 5];
String index = "3";
print(array[index]); // Throws the 'String is not a subtype of int' error
Similar to the previous example, the variable index
is a string with the value “3”. But when trying to access the element at index “3” in the array
, the error occurs because the index should be an integer, not a string.
Solution:
To fix this error, make sure that you use an integer value as the index when accessing items from a list or an array. If you have a string as the index, you can convert it to an integer using the appropriate parsing method. For example:
List<int> numbers = [1, 2, 3, 4, 5];
String indexAsString = "2";
int index = int.parse(indexAsString);
print(numbers[index]); // Prints the value at index 2, which is 3
In the modified code, we first convert the string indexAsString
to an integer using int.parse()
. Then, we use the integer index
to access the item at index 2 in the numbers
list.