Back to quest
Dart Basics & Data TypesLevel 13 / 32

Type Conversion

Converting between different data types

In Dart, variables are strongly typed, meaning you cannot simply treat a String like a number. Type conversion (or casting) is the process of explicitly transforming a value from one type to another—like turning the user input "25" (String) into the number 25 (int) so you can do math with it.

1. Converting Strings to Numbers

This is the most common conversion scenario, especially when dealing with user input or API data. Dart provides parse and tryParse methods for this purpose.

Parsing Integers and Doubles

example.dart
1String ageText = '25';
2String priceText = '19.99';
3 
4// 1. Using parse (Throws error if invalid)
5int age = int.parse(ageText);
6double price = double.parse(priceText);
7 
8print(age + 5); // 30
9print(price * 2); // 39.98
10 
11// 2. Using tryParse (Returns null if invalid - Safer)
12String invalidInput = 'hello';
13int? val = int.tryParse(invalidInput);
14 
15if (val == null) {
16 print('Invalid number!');
17} else {
18 print('Number is $val');
19}

HintAlways use tryParse if you are unsure about the input format (e.g., user typing text instead of a number) to prevent your app from crashing.

2. Converting Numbers to Strings

When you want to display a number in a Text widget or print it, you must convert it to a String. This is done using the .toString() method or String Interpolation.

Formatting Numbers as Text

example.dart
1int distance = 100;
2double temperature = 25.6789;
3 
4// Method A: .toString()
5String label = distance.toString();
6 
7// Method B: Interpolation (Preferred)
8String message = 'Distance: $distance km';
9 
10// Method C: Formatting decimals (toStringAsFixed)
11// Keeps only 1 decimal point
12String tempDisplay = temperature.toStringAsFixed(1);
13 
14print(tempDisplay); // Output: "25.7" (Rounded)

HinttoStringAsFixed(n) is incredibly useful for displaying prices or measurements neatly.

3. Casting with "as"

Sometimes Dart knows a variable is a generic type (like dynamic or Object), but you know it is actually a specific type. You can use the as keyword to tell Dart to treat it as that specific type.

Explicit Casting

example.dart
1dynamic randomValue = 'I am actually a String';
2 
3// Telling Dart: "Trust me, this is a String"
4String text = randomValue as String;
5 
6print(text.length); // Works!
7 
8// ⚠️ DANGER: If you are wrong, the app crashes!
9// int number = randomValue as int; // ❌ Runtime Error: type 'String' is not a subtype of type 'int'

HintUse as carefully. It is safer to use is checks first: if (value is String) { ... }.

Loot collected

Key takeaways
  • Use int.parse() or double.parse() to convert Strings to numbers.
  • Use tryParse() to safely handle invalid inputs without crashing.
  • Use .toString() or interpolation ($var) to convert numbers to text.
  • Use .toStringAsFixed(n) to round decimal numbers to n places.
  • The as keyword allows manual casting but throws an error if the types don't match.

Side quests

Practice exercises

1

Exercise 1: Basic Math

Given the strings "10" and "5.5", convert them to numbers and print their sum.

Reveal solution
solution.dart
1String a = '10'; String b = '5.5';
2print(int.parse(a) + double.parse(b)); // 15.5
2

Exercise 2: Safe Parsing

Try to parse the string "abc" into an integer using tryParse. Print "Error" if it returns null.

Reveal solution
solution.dart
1int? value = int.tryParse('abc');
2if (value == null) print('Error');
3

Exercise 3: Formatting

Convert the number 3.14159 into a String with only 2 decimal places.

Reveal solution
solution.dart
1double pi = 3.14159;
2print(pi.toStringAsFixed(2)); // '3.14'
Party chat

Comments