Type Conversion trong Dart
🎯 Mục tiêu: Chuyển đổi kiểu dữ liệu an toàn trong Dart.
💡 Parse String → Number
// 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
// 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🔧 Type Checking và Casting
// 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✅ Checklist
- Dùng
tryParsethay vìparse - Dùng
ischo type checking - Cẩn thận với
as- có thể throw
Last updated on