| 类型转换 | 方法 |
|---|---|
| String → int | int.parse() / int.tryParse() |
| String → double | double.parse() / double.tryParse() |
| int → String | toString() |
| double → String | toString() / toStringAsFixed(n) |
| String → DateTime | DateTime.parse() |
| DateTime → String | toIso8601String() / intl.DateFormat() |
| 时间戳 → DateTime | DateTime.fromMillisecondsSinceEpoch() |
| DateTime → 时间戳 | millisecondsSinceEpoch |
字符串 ↔ 数字
字符串 → int / double
void main() {
String intStr = '123';
String doubleStr = '45.67';
int intValue = int.parse(intStr);
double doubleValue = double.parse(doubleStr);
print(intValue); // 123
print(doubleValue); // 45.67
}
⚠️ 注意:如果字符串不是合法数字,会抛出
FormatException,可以用tryParse安全解析。
int? safeInt = int.tryParse('abc'); // null
int / double → 字符串
void main() {
int intValue = 123;
double doubleValue = 45.67;
String intStr = intValue.toString();
String doubleStr = doubleValue.toStringAsFixed(2); // 保留2位小数
print(intStr); // '123'
print(doubleStr); // '45.67'
}
字符串 ↔ 时间
字符串 → DateTime
void main() {
String dateStr = '2025-09-15 14:30:00';
DateTime dt = DateTime.parse(dateStr);
print(dt); // 2025-09-15 14:30:00.000
}
⚠️ 要求格式符合
yyyy-MM-dd HH:mm:ss或yyyy-MM-ddTHH:mm:ssZ等 ISO 8601 格式。
DateTime → 字符串
void main() {
DateTime now = DateTime.now();
String iso = now.toIso8601String(); // 标准格式
String custom = '${now.year}-${now.month}-${now.day}'; // 自定义格式
print(iso); // 2025-09-15T14:30:00.123
print(custom); // 2025-9-15
}
⚡ 如果想格式化为更灵活的格式(如
yyyy/MM/dd HH:mm),可以用 包的DateFormat。
import 'package:intl/intl.dart';
void main() {
DateTime now = DateTime.now();
String formatted = DateFormat('yyyy/MM/dd HH:mm').format(now);
print(formatted); // 2025/09/15 14:30
}
数字 ↔ 时间(时间戳)
时间戳 → DateTime
void main() {
int millis = 1631701800000; // 毫秒时间戳
DateTime dt = DateTime.fromMillisecondsSinceEpoch(millis);
print(dt); // 2021-09-15 14:30:00.000
}
DateTime → 时间戳
void main() {
DateTime now = DateTime.now();
int millis = now.millisecondsSinceEpoch;
print(millis); // 1631701800000
}