Type Conversion
In Dart, type conversion refers to the process of converting a value from one data type to another. Dart supports both implicit and explicit type conversion.
Implicit Type Conversion
Implicit type conversion is done automatically when operations involving different numeric types are performed.
Example
In the following example, the data type of intValue
is implicitly converted from an int
(10) to a double
(10.0) to perform the addition with doubleValue
:
void main() {int intValue = 10;double doubleValue = .5;// Demonstrating implicit type conversion during arithmetic operationdouble result = intValue + doubleValue;print(result);}
This produces the following output:
10.5
Explicit Type Conversion
Explicit type conversion or type casting is done by programmers using predefined functions or methods to convert values from one type to another. The following are the methods for explicit type conversion:
toString()
: Converts a value to a string.toDouble()
: Converts a value to a double.toInt()
: Converts a value to an integer.parse()
: Converts a string to a numeric type.tryParse()
: Similar toparse()
, but returnsnull
if the conversion fails.
Example
In this example, the toString()
method is explicitly called on intValue
to convert the default integer type to a string:
void main() {var intValue = 42;var stringValue = intValue.toString(); // Explicit toString() callprint(stringValue);}
The output is as follows:
42
Type Conversion
- .parse()
- Converts a string representation of data into a specified data type.
- .toDouble()
- Returns the double representation of the numerical value.
- .toInt()
- Converts numeric values to integers.
- .toString()
- Converts the object into a string representation.
- .toStringAsExponential()
- Converts a number to its exponential notation in a string format.
- .toStringAsFixed()
- Converts a number to a string with a fixed number of decimal places.
- .toStringAsPrecision()
- Converts a number to a double and returns a string representation with the specified number of significant digits.
- .tryParse()
- Parses a string and converts it into the given data type.
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.