Flutter

How to solve ‘int is not a sub type of string’ in Flutter

In Flutter, just like in many programming languages, int and String are different data types and are not interchangeable. You often this error int is not a sub type of string’ in flutter. Let’s understand the reason of this error and learn how to solve this.

Integer

An int (short for integer) is a numerical data type that represents whole numbers, such as -2, -1, 0, 1, 2, and so on. It is typically used for mathematical operations.

String

A String is a sequence of characters. It is used to represent text or other types of data. which can be represented as a sequence of characters.

Flutter data types

In Flutter, int and String are not subtypes of each other, and cannot be used interchangeably. This means that you cannot assign an int value to a String variable, or vice versa, without first converting the data type. For example, if you have an int variable called myInt, and you want to use it as a String, you would need to convert it using the toString() method like this: myInt.toString().

Similarly, if you have a String variable called myString, and you want to use it as an int, you would need to convert it using the int.parse() method like this: int.parse(myString).

It’s important to keep in mind the data type of your variables when working in Flutter, as using the wrong data type can lead to errors and unexpected behavior.

Errors in Flutter

int is not a sub type of string’

this is a common error in flutter, when you are dealing with data types. If you are facing this issue while fetching data from an API, then you should verify the data types of your model and json response of API.

This error commonly occurs when a json response contains a value of type int but we have declared that key as String in our model class.

For example we have a json

{
  "id":1,
  "name":"John"
  "age":27
}

And we created a model class, and parsing this json in to this class.

class Person{ 
    Int id;
    String name;
    String age;
}

When we will parse our json response into this model class. We will face this error ‘int is not a sub type of string’, because we have declared age as String in our class, but the type of age is integer in json.

Solution of ‘int is not a sub type of string

To solve this error, we just have to change the type of our age variable from String to integer. Because our json response contains age as integer.

Another common error of flutter is ‘Future‘ is not a subtype of type ‘String’ in type cast.

Hope this will help you. Thank you for reading

Leave a Reply

Your email address will not be published. Required fields are marked *