How to convert String to int or double in Dart/Flutter
Restored from an archived FlutterDocs resource. Code examples and APIs may refer to earlier Flutter/Dart SDK versions.
In this example, we are going to show you how to convert or parse the String variables to int or double in Dart and Flutter. You may need to convert string to int or double for mathematical purposes. See the examples below:
How to Parse String to Int in Dart/Flutter
int a = int.parse(sourceString);
Examples:
String a = "4";
String b = "5";
int c = int.parse(a);
print(c); //output: 4
int d = int.parse(a) + int.parse(b);
print(d); //puutput: 9
Unsupported Format:
String e = "df53df4";
int f = int.parse(e);
print(f); //error: Invalid radix-10 numbe
How to Parse String to double in Dart/Flutter:
double aa = double.parse(sourceString);
Example:
String aa = "4.5";
String bb = "5.3";
double cc = double.parse(aa);
print(cc); //output: 4.5
double dd = double.parse(aa) + double.parse(bb);
print(dd); //output: 9.8
Unsupported Format:
String ee = "dfgdf34.45df";
double ff = double.parse(ee);
print(ff); //output: Invalid double dfgdf34.45df
In this way, you can convert or parse a String to an integer or a double in Dart/Flutter.