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.
Use int.parse() to convert a String containing a number into an integer:
void main() { String variable = '50'; // Convert String to int int numero = int.parse(variable); print(numero); // 50 (as integer) print(numero + 10); // 60 (can now do math)}
int.parse() will throw an error if the string doesn’t contain a valid integer. For example, int.parse('hello') will crash your program.
Here’s a comprehensive example showing all the common conversions:
void main() { // String to int String variable = '50'; int numero = int.parse(variable); print('String to int: $numero'); // int to String String valor = numero.toString(); print('int to String: $valor'); // int to double int numeroUno = 123; double dobleUno = numeroUno.toDouble(); print('int to double: $dobleUno'); // double to int double dobleDos = 1234.56789; int entero = dobleDos.toInt(); print('double to int: $entero'); // String to double String textoDecimal = '99.99'; double precio = double.parse(textoDecimal); print('String to double: $precio'); // double to String String precioTexto = precio.toString(); print('double to String: $precioTexto');}
void main() { // User inputs are always strings String userInput = '25'; // Simulating user input // Convert to int for calculations int edad = int.parse(userInput); if (edad >= 18) { print('You are an adult'); } else { print('You are a minor'); }}