Type Conversion
We can convert between data types, let's see how...
String to Number
void main() {
String num = '42';
int numAsInt = int.parse(num);
print(numAsInt);
print(numAsInt.runtimeType);
}
42 int
Notice that the data type of num variable changed from a string to an int in line 3 by using the int.parse() method.
We verified the change of data type of the num variable in line 6 by printing the runtimeType of num variable.
Parsing error
When we try to parse a non-parsable variable, we face an error.
Let’s say we stored a string, 'hello' in a variable. Now we cannot parse an int from this variable, because we cannot get any int value from
a non-parsable string variable.
In this particular case, the parse() method will throw an exception and crash our program.
In production code, we need to catch the exception so as to to prevent the crash.
To fix the parsing issue, we can use the tryParse() method instead.
void main() {
print('Enter an odd number: ');
String? userInput = stdin.readLineSync();
int? number = int.tryParse(userInput ?? "");
if (number != null) {
print('Valid number: $number');
} else {
print('Invalid number, please enter a valid number!');
}
}
Enter an odd number: 3 Valid number: 3
In the above highlighted line of code, notice there is the use of ?? operator. That is called a null-coalescing operator.
In that particular line of code, the null-coalescing operator is used to tell the dart compiler:
if the user entered a non-null input, then store the value of the variable
userInputin number, and else if the user entered a null input, then store an empty string instead.
We cannot use parse() instead of tryParse() in the above code block.
This is because int.parse('hello') throws a FormatException. We can use try catch methods for handling exceptions, but this is
an exception occuring from parsing.
So, in this case the tryParse() method is best suitable handling invalid input from the user.
Number to String
void main() {
double price = 3473.5632;
String priceText = price.toString();
String priceShort = price.toStringAsFixed(2);
print('$priceText -> Runtime type is ${priceText.runtimeType}');
print(priceShort);
}
3473.5632 -> Runtime type is String 3473.56
In the above code, we used toString() method on a double value to convert it to a string.
We also used another version of the toString() method, i.e., toStringAsFixed(2) to limit the double value up to
2 decimal places, and then converted to a string.
Notice the number
2passed as the argument inside thetoStringAsFixed()method.