dart

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Dart

Dart

Modern Dart development with null safety, pattern matching, and Flutter integration.
具备空安全、模式匹配和Flutter集成的现代Dart开发。

When to Use

使用场景

  • Working with
    .dart
    files
  • 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
    const
    constructors when possible
  • Prefer
    final
    for immutable variables
  • Use named parameters with
    required
  • Follow effective_dart lints
Don't:
  • Use
    dynamic
    when type is known
  • Force unwrap with
    !
    unnecessarily
  • Create God classes (keep small)
  • Ignore
    late
    initialization errors
建议:
  • 尽可能使用
    const
    构造函数
  • 优先为不可变变量使用
    final
  • 使用带
    required
    的命名参数
  • 遵循effective_dart代码规范
避免:
  • 已知类型时使用
    dynamic
  • 不必要地使用
    !
    强制解包
  • 创建上帝类(保持类的精简)
  • 忽略
    late
    初始化错误

Troubleshooting

问题排查

ErrorCauseSolution
Null check operator used on null
Using
!
on null value
Add null check first
LateInitializationError
Accessing late var before initInitialize before access
type 'Null' is not a subtype
Type mismatch with nullCheck nullable types
错误信息原因解决方案
Null check operator used on null
对空值使用了
!
运算符
先添加空值检查
LateInitializationError
在初始化前访问了late变量访问前先初始化
type 'Null' is not a subtype
与空值存在类型不匹配检查可空类型

References

参考资料