
This tutorial shows multiple ways to convert integer to String in Dart or Flutter programming language
The string is a string of numbers enclosed in double quotes An integer is a primitive type of a number
Both represent different types, Automatic conversions are not possible. So, We have to manually Convert String into Int or Int to String with examples
It is easy to parse String to Int in Dart with inbuilt methods
How to parse String to Integer in Dart programming example
There are multiple ways we can do the conversion.
- use parseInt method in Integer class
integer
class provides static parse()
method, takes an input string, and converts into int type.
Syntax:
int parse(String str, {int? radix})
Argument
is a string of a number, if the string contains non-numeric value, It throws Uncaught Error: FormatException:
Radix
is an optional parameter and values are 10(default convert to decimal),8,2
Here is an example
void main() {
var str='123';
var number = int.parse(str);
print(number == 123); // true
print(number.runtimeType); // int
}
parse method throws an error for invalid string of numbers such as non-numeric characters and null.
The below parse method throws Uncaught Error: FormatException: abc
void main() {
var str='abc';
var number = int.parse(str);
print(number == 123); // true
print(number.runtimeType); // int
}
-
tryParse method in int
tryParse
in the Integer class is advanced to theparse
method.It handles runtime exceptions and returns a null if you passed a string of non-numeric invalid numbers.
void main() {
var str='abc';
var number = int.tryParse(str);
print(number); // null
print(number.runtimeType); // Null
}
How to Convert Int to String in Dart with example?
There are multiple ways to convert integer to String in dart.
-
toString()
-
toRadixString();
-
Append string with interpolation syntax
-
toString() method
Every class in dart provides the toString() method.
Integer method provides this method and return string version of a number.
void main() {
int number = 1;
String str = number.toString();
print(str); // 1
print(str.runtimeType);// String
}
- toRadixString() method
Syntax:
int toRadixString(int radix)
This method takes radix values such as 16 for hexadecimal, 8 for octal number, 10 default for decimal numbers.
Here is an example
void main() {
int number = 12;
String str = number.toRadixString(10);
print(str); //12
print(str.runtimeType); //String
assert(str is String); // true
}
- append a string with interpolation syntax
String interpolation (${}) enclosed in single or double quotes You can append strings or plain numbers with interpolation syntax.
Here is an example
void main() {
int number = 45;
String str = '${number}';
print(str); // 45
print(str.runtimeType);// String
assert(str is String); // true
}
Conclusion
To summarize, Learned how to convert string to integer vice versa in Dart language with examples