Bỏ qua để đến nội dung

Chuyển đổi kiểu dữ liệu (Type Conversion)

🎯 Mục tiêu: Chuyển đổi kiểu dữ liệu an toàn trong Dart.


// Safe parsing (returns null if failed)
int? a = int.tryParse("123"); // 123
int? b = int.tryParse("abc"); // null
double? c = double.tryParse("3.14"); // 3.14
// Với default value
int age = int.tryParse(input) ?? 0;

// Number → String
String s = 42.toString(); // "42"
String d = 3.14159.toStringAsFixed(2); // "3.14"
// int ↔ double
int i = 3.14.toInt(); // 3
double d = 42.toDouble(); // 42.0
int r = 3.14.round(); // 3

// is - type check
if (value is String) {
print(value.length); // Auto-cast
}
// as - explicit cast
String s = obj as String;
String? s2 = obj as String?; // Nullable cast

  • Dùng tryParse thay vì parse
  • Dùng is cho type checking
  • Cẩn thận với as - có thể throw