Convert String to Int

Create Free Backend With Appwrite

Convert String To Int In Dart

targets

The String is the textual representation of data, whereas int is a numeric representation without a decimal point. While coding in must of the case, you need to convert data from one type to another type. In dart, you can convert String to int by using the int.parse() method.

int.parse("String");

targets

You can replace String with any numeric value and convert String to int. Make sure you have numeric value there. To know more see the example below.

Example To Convert String to Int

This program converts String to int. You can view type of variable with .runtimeType.

void main(){
String value = "10";
int numericValue = int.parse(value);
print("Type of value is ${value.runtimeType}");
print("Type of numeric value is ${numericValue.runtimeType}");
}

targets

Show Output
Run Online

Example 2 To Convert String to Int

This program first converts String to int and finds the sum of two numbers.

void main(){
String value = "10";

int num2 = 20;
int num1 = int.parse(value);

int sum = num1 + num2;

print("Type sum is $sum");
}

targets

Show Output
Run Online

Things To Remember While Casting String To Int

You must be sure that String could convert the to int. If it doesn’t convert to int, it will throw an exception. You can use the try-catch statement to show your custom message. If you don’t know exception handling in dart learn from here.

Example With Try Catch

This program throws an exception because you can’t convert “hello” to int. In this situation, you can use the try-catch exception to display your custom message.

void main(){
try {
String value = "hello";
int numericValue = int.parse(value);
print("Type of numeric value is ${numericValue.runtimeType}");

  }
catch(ex){
print("Something went wrong.");
}

}

targets

Show Output
Run Online

targets