Skip to content
AgileLogics
4 min read

Type Conversion

Prerequisites: Working with nullable values

Dart never converts between types automatically — you call a conversion method.

Numbers and strings

void main() {
  print(7.toDouble());
  print(2.9.toInt());
  print(42.toString() + '!');
  print(3.14159.toStringAsFixed(1));
  print(int.parse('42') + 1);
  print(double.parse('3.5') * 2);
  print(num.parse('7'));
}
7.0
2
42!
3.1
43
7.0
7

toInt() on a double truncates — it drops the decimals.

parse vs tryParse

  • int.parse, double.parse — throw a FormatException for invalid text.
  • int.tryParse, double.tryParse — return null instead.
void main() {
  final inputs = ['42', '3.5', 'abc', ' 7'];

  for (final input in inputs) {
    final number = int.tryParse(input);
    if (number != null) {
      print("'$input' → $number");
    } else {
      print("'$input' → not a whole number");
    }
  }
}
'42' → 42
'3.5' → not a whole number
'abc' → not a whole number
' 7' → 7

Surrounding whitespace is ignored (' 7' parses as 7), but anything else that isn't part of a whole number — like the decimal point in '3.5' — makes int.tryParse return null. Use double.tryParse for decimals.

Common mistakes

  • Using int.parse on user input and crashing on the first typo. Use tryParse and handle null.