Introduction
Type conversion (also called type casting) is the process of converting a value from one data type to another. In Dart, you’ll often need to convert between types, such as turning a String into an int, or an int into a double.Dart performs explicit type conversion - you must explicitly convert types using built-in methods. This prevents accidental type-related bugs.
Common Type Conversions
String → int
Parse text to integer
int → String
Convert number to text
int → double
Convert integer to decimal
double → int
Convert decimal to integer
String → double
Parse text to decimal
double → String
Convert decimal to text
String to int Conversion
Useint.parse() to convert a String containing a number into an integer:
Safe Parsing with tryParse
For safer parsing that won’t crash your program, useint.tryParse():
int to String Conversion
Use.toString() to convert any number to a String:
Working with Large Numbers
int to double Conversion
Use.toDouble() to convert an integer to a double (decimal number):
double to int Conversion
Use.toInt() to convert a double to an integer. This truncates the decimal part (doesn’t round):
Rounding Doubles to Integers
If you want to round instead of truncate, use these methods:String to double Conversion
Usedouble.parse() to convert a String to a double:
Complete Conversion Example
Here’s a comprehensive example showing all the common conversions:Practical Use Cases
User Input Conversion
Calculations with Mixed Types
Formatting Numbers for Display
Conversion Methods Summary
Error Handling
Key Takeaways
- Use
int.parse()orint.tryParse()to convert String to int - Use
double.parse()ordouble.tryParse()to convert String to double - Use
.toString()to convert any number to String - Use
.toDouble()to convert int to double - Use
.toInt()to convert double to int (truncates decimals) - Use
.round(),.floor(), or.ceil()for rounding doubles - Always handle potential parsing errors with
tryParse()methods