dart
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseDart
Dart
Modern Dart development with null safety, pattern matching, and Flutter integration.
具备空安全、模式匹配和Flutter集成的现代Dart开发。
When to Use
使用场景
- Working with files
.dart - Building Flutter mobile/web/desktop apps
- Server-side Dart development
- Creating packages for pub.dev
- 处理.dart文件
- 构建Flutter移动/网页/桌面应用
- 服务端Dart开发
- 为pub.dev创建包
Quick Start
快速入门
dart
class User {
final String id;
final String name;
final String email;
const User({required this.id, required this.name, required this.email});
factory User.fromJson(Map<String, dynamic> json) => User(
id: json['id'] as String,
name: json['name'] as String,
email: json['email'] as String,
);
}dart
class User {
final String id;
final String name;
final String email;
const User({required this.id, required this.name, required this.email});
factory User.fromJson(Map<String, dynamic> json) => User(
id: json['id'] as String,
name: json['name'] as String,
email: json['email'] as String,
);
}Core Concepts
核心概念
Null Safety
Null Safety
dart
// Non-nullable by default
String name = 'John';
// Nullable with ?
String? maybeNull;
// Late initialization
late final String lazyInit;
// Null-aware operators
String greeting = person?.name ?? 'Guest';
person?.address?.city;dart
// 默认非空
String name = 'John';
// 使用?标记可空
String? maybeNull;
// 延迟初始化
late final String lazyInit;
// 空感知运算符
String greeting = person?.name ?? 'Guest';
person?.address?.city;Records & Pattern Matching (Dart 3)
Records & Pattern Matching (Dart 3)
dart
// Records
(String, int) getPerson() => ('John', 25);
// Destructuring
final (name, age) = getPerson();
// Switch expressions with patterns
String describe(Object obj) => switch (obj) {
int i when i < 0 => 'negative',
int i => 'positive: $i',
String s => 'string: $s',
_ => 'unknown',
};
// Sealed classes
sealed class Result<T> {}
class Success<T> extends Result<T> { final T value; Success(this.value); }
class Failure<T> extends Result<T> { final String error; Failure(this.error); }dart
// 记录类型
(String, int) getPerson() => ('John', 25);
// 解构
final (name, age) = getPerson();
// 带模式的Switch表达式
String describe(Object obj) => switch (obj) {
int i when i < 0 => 'negative',
int i => 'positive: $i',
String s => 'string: $s',
_ => 'unknown',
};
// 密封类
sealed class Result<T> {}
class Success<T> extends Result<T> { final T value; Success(this.value); }
class Failure<T> extends Result<T> { final String error; Failure(this.error); }Common Patterns
常见模式
Async/Await
Async/Await
dart
Future<User> fetchUser(String id) async {
final response = await http.get(Uri.parse('$baseUrl/users/$id'));
if (response.statusCode != 200) {
throw Exception('Failed to load user');
}
return User.fromJson(jsonDecode(response.body));
}
// Parallel execution
Future<void> loadData() async {
final results = await Future.wait([
fetchUser('1'),
fetchOrders('1'),
]);
}
// Streams
Stream<int> countStream(int max) async* {
for (int i = 0; i < max; i++) {
await Future.delayed(Duration(seconds: 1));
yield i;
}
}dart
Future<User> fetchUser(String id) async {
final response = await http.get(Uri.parse('$baseUrl/users/$id'));
if (response.statusCode != 200) {
throw Exception('Failed to load user');
}
return User.fromJson(jsonDecode(response.body));
}
// 并行执行
Future<void> loadData() async {
final results = await Future.wait([
fetchUser('1'),
fetchOrders('1'),
]);
}
// 流
Stream<int> countStream(int max) async* {
for (int i = 0; i < max; i++) {
await Future.delayed(Duration(seconds: 1));
yield i;
}
}Extensions
Extensions
dart
extension StringExtension on String {
String capitalize() =>
isEmpty ? this : '${this[0].toUpperCase()}${substring(1)}';
bool get isValidEmail =>
RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$').hasMatch(this);
}dart
extension StringExtension on String {
String capitalize() =>
isEmpty ? this : '${this[0].toUpperCase()}${substring(1)}';
bool get isValidEmail =>
RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$').hasMatch(this);
}Best Practices
最佳实践
Do:
- Use constructors when possible
const - Prefer for immutable variables
final - Use named parameters with
required - Follow effective_dart lints
Don't:
- Use when type is known
dynamic - Force unwrap with unnecessarily
! - Create God classes (keep small)
- Ignore initialization errors
late
建议:
- 尽可能使用构造函数
const - 优先为不可变变量使用
final - 使用带的命名参数
required - 遵循effective_dart代码规范
避免:
- 已知类型时使用
dynamic - 不必要地使用强制解包
! - 创建上帝类(保持类的精简)
- 忽略初始化错误
late
Troubleshooting
问题排查
| Error | Cause | Solution |
|---|---|---|
| Using | Add null check first |
| Accessing late var before init | Initialize before access |
| Type mismatch with null | Check nullable types |
| 错误信息 | 原因 | 解决方案 |
|---|---|---|
| 对空值使用了 | 先添加空值检查 |
| 在初始化前访问了late变量 | 访问前先初始化 |
| 与空值存在类型不匹配 | 检查可空类型 |