外观
Dart 语言核心指南
约 1642 字大约 5 分钟
2025-08-24
1. 基础语法
1.1 变量声明
var:类型由赋值自动推断,最常用的变量声明方式。
var name = "Kimi"; // 自动推断为 String 类型
var age = 25; // 自动推断为 int 类型final:运行时只可赋值一次,适合不希望被修改但需要在运行时确定值的场景。
final String name = "Kimi"; // 声明时必须初始化
final DateTime now = DateTime.now(); // 运行时确定的值const:编译时常量,值在编译时就完全确定。
const int maxUsers = 100;
const List<String> colors = ['red', 'green', 'blue'];最佳实践:优先使用
final和const,仅在确实需要重新赋值时使用var。
1.2 基本数据类型
| 类型 | 示例 | 说明 |
|---|---|---|
int | int age = 25; | 整数类型 |
double | double height = 1.75; | 浮点数类型 |
String | String name = "Kimi"; | 字符串类型 |
bool | bool isStudent = true; | 布尔类型 |
List | List<String> names = ["Kimi", "Alice"]; | 有序集合,可重复元素 |
Map | Map<String, int> ages = {"Kimi": 25}; | 键值对集合 |
Set | Set<int> numbers = {1, 2, 3}; | 无序集合,不允许重复元素 |
常用技巧:
- 字符串插值:
print("Name: $name, Age: $age");- 多行字符串:使用三个引号
"""或'''- 空安全:Dart 2.12+ 默认启用空安全,使用
?表示可空类型:String? nullableName;
2. 流程控制
2.1 条件语句
if/else:最常用的条件判断
if (age >= 18) {
print("Adult");
} else if (age >= 13) {
print("Teenager");
} else {
print("Child");
}三元运算符:简化简单的条件判断
String status = isAdult ? "Adult" : "Minor";2.2 循环语句
for 循环:最常用的循环方式
// 标准 for 循环
for (int i = 0; i < 5; i++) {
print(i);
}
// 遍历集合
List<String> names = ["Kimi", "Alice", "Bob"];
for (String name in names) {
print(name);
}while 循环:当条件满足时执行
int i = 0;
while (i < 5) {
print(i);
i++;
}do-while 循环:至少执行一次
int i = 0;
do {
print(i);
i++;
} while (i < 5);3. 函数
3.1 基本函数
// 无返回值函数
void greet(String name) {
print("Hello, $name!");
}
// 带返回值函数
int add(int a, int b) {
return a + b;
}3.2 箭头函数
适用于单行函数体,简洁明了
int subtract(int a, int b) => a - b;
String formatName(String first, String last) => '$first $last';3.3 参数类型
命名参数(带 {}):提高代码可读性,参数顺序不重要
void printUser({required String name, int? age, String? city}) {
print("Name: $name, Age: $age, City: $city");
}
// 调用
printUser(name: "Kimi", age: 25);可选位置参数(带 []):参数按顺序可选
void printUser(String name, [int? age, String? city]) {
print("Name: $name, Age: $age, City: $city");
}
// 调用
printUser("Kimi", 25);最佳实践:
- 优先使用命名参数,提高代码可读性
- 对必填参数使用
required关键字- 避免过多参数,考虑使用对象封装
4. 面向对象编程
4.1 类与对象
class Person {
String name;
int age;
// 构造函数简写
Person(this.name, this.age);
// 方法
void greet() {
print("Hello, my name is $name and I am $age years old.");
}
// 计算属性
int get birthYear => DateTime.now().year - age;
}4.2 继承
class Student extends Person {
String school;
// 调用父类构造函数
Student(String name, int age, this.school) : super(name, age);
void study() {
print("I am studying at $school.");
}
// 重写方法
@override
void greet() {
super.greet();
print("I am a student at $school.");
}
}4.3 Mixins(常用替代继承的方式)
// 定义 mixin
mixin Loggable {
void log(String message) {
print('[LOG] $message');
}
}
// 使用 mixin
class User with Loggable {
String name;
User(this.name);
void sayHello() {
log('Saying hello');
print("Hello, $name!");
}
}
// 多 mixin
class AdminUser with Loggable, Authenticatable {
// ...
}5. 异步编程(核心重点)
5.1 Future 与 async/await
// 异步函数返回 Future
Future<String> fetchData() async {
await Future.delayed(Duration(seconds: 1));
return "Data from server";
}
// 使用 async/await 调用
void process() async {
try {
String data = await fetchData();
print("Received: $data");
} catch (e) {
print("Error: $e");
}
}5.2 异步错误处理
Future<void> handleData() async {
try {
String data = await fetchData();
print(data);
} on TimeoutException {
print("Request timed out");
} on NetworkException catch (e) {
print("Network error: $e");
} catch (e, stackTrace) {
print("Unexpected error: $e");
print("Stack trace: $stackTrace");
} finally {
print("Operation completed");
}
}5.3 多个异步操作
// 顺序执行
Future<void> sequentialProcess() async {
String data1 = await fetchFirst();
String data2 = await fetchSecond(data1);
print("$data1, $data2");
}
// 并行执行
Future<void> parallelProcess() async {
var results = await Future.wait([
fetchFirst(),
fetchSecond(),
fetchThird()
]);
print(results);
}6. 错误处理
void divide(int a, int b) {
try {
int result = a ~/ b;
print("Result: $result");
} on IntegerDivisionByZeroException {
print("Cannot divide by zero");
} catch (e) {
print("An error occurred: $e");
} finally {
print("Division operation completed");
}
}最佳实践:
- 不要过度使用 try/catch,只捕获你能处理的异常
- 为自定义异常创建特定类
- 在应用边界处捕获异常(如UI事件处理)
7. 泛型(常用场景)
// 泛型函数
T firstElement<T>(List<T> list) {
if (list.isEmpty) throw StateError('List is empty');
return list.first;
}
// 泛型类
class Cache<T> {
final Map<String, T> _storage = {};
void setValue(String key, T value) {
_storage[key] = value;
}
T? getValue(String key) {
return _storage[key];
}
}
// 使用
Cache<String> stringCache = Cache<String>();
stringCache.setValue('greeting', 'Hello');
String? greeting = stringCache.getValue('greeting');8. 实用技巧与最佳实践
8.1 空安全最佳实践
// 可空类型
String? nullableName;
// 空值检查
if (nullableName != null) {
print(nullableName.length);
}
// 空值合并运算符
String name = nullableName ?? 'Guest';
// 空值断言(谨慎使用)
print(nullableName!.length); // 如果 nullableName 为 null,会抛出异常
// 条件成员访问
print(nullableName?.length); // 如果为 null,返回 null 而不是抛出异常8.2 集合操作技巧
// List 操作
List<int> numbers = [1, 2, 3, 4, 5];
List<int> doubled = numbers.map((n) => n * 2).toList();
List<int> evens = numbers.where((n) => n.isEven).toList();
bool hasOdd = numbers.any((n) => n.isOdd);
int sum = numbers.fold(0, (prev, el) => prev + el);
// Map 操作
Map<String, int> ages = {"Kimi": 25, "Alice": 22};
Map<String, int> adultAges = ages..removeWhere((name, age) => age < 18);8.3 扩展方法(Extension Methods)
// 定义扩展方法
extension StringExtensions on String {
bool get isNumeric => int.tryParse(this) != null;
String repeatNTimes(int n) => List.filled(n, this).join();
}
// 使用扩展方法
print("123".isNumeric); // true
print("hi".repeatNTimes(3)); // "hihihi"9. 常见陷阱与避免方法
异步陷阱:忘记使用
await导致返回 Future 而不是实际值// 错误 String data = fetchData(); // 正确 String data = await fetchData();空安全陷阱:未检查可空类型直接访问
// 错误 String? name; print(name.length); // 可能抛出异常 // 正确 print(name?.length ?? 0);集合修改陷阱:在遍历时修改集合
// 错误 for (var item in list) { if (item == 'remove') list.remove(item); // 可能导致 Concurrent modification error } // 正确 list.removeWhere((item) => item == 'remove');
10. 总结
本文涵盖了 Dart 语言最核心、最常用的 80% 知识点,包括:
- 基础语法与变量声明
- 常用数据类型与集合操作
- 流程控制语句
- 函数定义与参数处理
- 面向对象核心概念(类、继承、Mixins)
- 重点:异步编程(Future 与 async/await)
- 错误处理
- 泛型基础
- 实用技巧与最佳实践
掌握这些内容足以应对大多数 Dart 开发场景,特别是 Flutter 应用开发。随着经验增长,可以按需学习更高级的主题,如更复杂的 Stream 操作、元编程等。
