Type conversion
suggest changeDart is a strongly typed, sound programming language. Unlike JavaScript or PHP, Dart does not perform implicit type coercion (for instance, an int will not automatically coerce into a String or double). All conversions between incompatible types must be performed explicitly.
Number and String Conversions
Parsing Strings to Numbers
Use parse() or tryParse() to convert strings into numeric values:
void main() {
// Parsing integers
final count = int.parse('42');
print(count + 8); // 50
// Parsing floating-point numbers
final price = double.parse('19.99');
print(price * 1.1);
// Parsing with hexadecimal or other radices
final hexColor = int.parse('FF00AA', radix: 16);
print(hexColor); // 16711850
// Safe parsing with tryParse (returns null on malformed input)
final invalid = int.tryParse('abc'); // null
final safePort = int.tryParse('invalid') ?? 8080;
print('Port: $safePort'); // 8080
}
Tip: Always prefer
tryParse()when handling external input (user input, JSON, or URL parameters) to avoid unhandledFormatExceptioncrashes.
Converting Numbers to Strings
void main() {
final count = 120;
print(count.toString()); // "120"
// Formatting decimals to fixed precision
final pi = 3.14159265;
print(pi.toStringAsFixed(2)); // "3.14"
print(pi.toStringAsFixed(4)); // "3.1416"
// Exponential format
print(1500000.toStringAsExponential(2)); // "1.50e+6"
// Radix conversion (e.g. integer to hex or binary string)
print(255.toRadixString(16)); // "ff"
print(5.toRadixString(2)); // "101"
}
Conversions Between Numbers (int and double)
Dart does not implicitly convert int to double or vice versa:
void main() {
final int count = 42;
// Explicit conversion to double
final double precise = count.toDouble();
print(precise); // 42.0
final double original = 7.89;
// Converting double to int via different rounding behaviors:
print(original.toInt()); // 7 (truncates toward zero)
print(original.truncate()); // 7
print(original.floor()); // 7 (largest integer <= value)
print(original.ceil()); // 8 (smallest integer >= value)
print(original.round()); // 8 (rounds to nearest integer)
}
Type Casting (as) vs Type Checking (is)
Type Promotion (Smart Casting)
When you check an object's type with is or is!, the Dart analyzer automatically promotes the variable to that type within the corresponding scope:
void processValue(Object val) {
if (val is String) {
// val is automatically promoted to String
print('String length: ${val.length}');
} else if (val is int) {
// val is automatically promoted to int
print('Integer doubled: ${val * 2}');
}
}
Explicit Casting (as)
Use the as operator only when you are certain of the underlying runtime type:
void handlePayload(dynamic payload) {
// If payload is not a Map, this throws a TypeError at runtime
final map = payload as Map<String, dynamic>;
print(map['username']);
}
Warning: Avoid unnecessary casts (
as). Useischecks or pattern matching to handle polymorphism safely withoutTypeErrorexceptions.
Pattern Matching with Dart 3
Dart 3 pattern matching provides a safe, exhaustive alternative to manual casting:
String describe(Object data) {
return switch (data) {
int n => 'Integer: $n (doubled: ${n * 2})',
double d => 'Double: ${d.toStringAsFixed(2)}',
String s && == '' => 'Empty string',
String s => 'String of length ${s.length}',
List<dynamic> list => 'List containing ${list.length} items',
_ => 'Unknown type: $data'
};
}
Collection Type Conversion
Transforming Lists and Sets
void main() {
final strings = ['10', '25', '42'];
// Map strings to integers
final numbers = strings.map((s) => int.parse(s)).toList();
print(numbers); // [10, 25, 42]
// Deduplicating a list by converting to a Set
final duplicates = [1, 2, 2, 3, 3, 3];
final uniqueSet = duplicates.toSet();
final uniqueList = uniqueSet.toList();
print(uniqueList); // [1, 2, 3]
}
Casting Generic Collections (cast() vs List.from())
list.cast<T>(): Creates a lazy type-checking wrapper view. If any element violates typeTupon access, a runtime error is thrown.List<T>.from(list)orlist.map(...).toList(): Eagerly creates a new typed list and checks all elements upfront.
void main() {
final dynamicList = <dynamic>[1, 2, 3];
// Eager type-safe conversion
final List<int> typedList = List<int>.from(dynamicList);
print(typedList); // [1, 2, 3]
}
Best Practices
- Use
tryParse()overparse(): Guard against malformed user input or network data without costlytry/catchblocks. - Rely on type promotion (
is): Let the compiler smart-cast values rather than using riskyasassertions. - Be cautious with
.cast(): UseList<T>.from()orlist.whereType<T>()instead of.cast<T>()to filter and validate collection types eagerly.