Skip to content

附录:Dart 核心知识点汇总 ​

1. 核心语法速记(按使用频率排序,附示例) ​

1.1 变量声明 ​

dart
// 类型推断
var name = 'Dart';

// 明确类型
String message = 'Hello World';
int age = 20;
double height = 1.75;
bool isActive = true;

// 可空类型
String? nullableString = null;
int? nullableInt;

// late 延迟初始化
late String lateVariable;
lateVariable = 'Initialized later';

1.2 函数定义 ​

dart
// 基本函数
int add(int a, int b) {
  return a + b;
}

// 箭头函数
int subtract(int a, int b) => a - b;

// 可选参数
String greet(String name, [String? message]) {
  return message != null ? 'Hello $name, $message' : 'Hello $name';
}

// 命名参数
void printUser({required String name, int? age}) {
  print('Name: $name, Age: ${age ?? 'Unknown'}');
}

// 函数作为参数
void performOperation(int a, int b, Function(int, int) operation) {
  print(operation(a, b));
}

1.3 流程控制 ​

dart
// if-else
if (age >= 18) {
  print('Adult');
} else if (age >= 13) {
  print('Teenager');
} else {
  print('Child');
}

// switch-case
switch (day) {
  case 'Monday':
    print('First day of week');
    break;
  case 'Friday':
    print('Last day of week');
    break;
  default:
    print('Other day');
}

// 循环
for (int i = 0; i < 5; i++) {
  print(i);
}

// 遍历集合
List<String> fruits = ['Apple', 'Banana', 'Orange'];
for (var fruit in fruits) {
  print(fruit);
}

// while 循环
int count = 0;
while (count < 3) {
  print(count);
  count++;
}

1.4 集合操作 ​

dart
// List
List<String> list = ['a', 'b', 'c'];
list.add('d');
list.remove('b');

// Set
Set<int> set = {1, 2, 3};
set.add(4);
set.contains(2); // true

// Map
Map<String, int> map = {'one': 1, 'two': 2};
map['three'] = 3;
map.containsKey('one'); // true

1.5 异步编程 ​

dart
// Future
Future<String> fetchData() async {
  await Future.delayed(Duration(seconds: 1));
  return 'Data fetched';
}

// 调用异步函数
void main() async {
  try {
    String data = await fetchData();
    print(data);
  } catch (e) {
    print('Error: $e');
  }
}

2. 数据类型、集合、函数常用方法汇总 ​

2.1 数据类型方法 ​

类型常用方法描述
Stringlength获取字符串长度
StringisEmpty检查是否为空
Stringcontains()检查是否包含子字符串
Stringsplit()分割字符串
Stringtrim()去除首尾空白
inttoString()转换为字符串
inttoDouble()转换为double
doubletoStringAsFixed()保留指定位数小数
booltoString()转换为字符串

2.2 集合方法 ​

集合常用方法描述
Listadd()添加元素
Listremove()移除元素
Listlength获取长度
ListisEmpty检查是否为空
Listcontains()检查是否包含元素
Listsort()排序
Listmap()映射转换
Listwhere()过滤元素
Setadd()添加元素
Setremove()移除元素
Setcontains()检查是否包含元素
Setunion()合并集合
MapputIfAbsent()不存在时添加
Mapremove()移除键值对
MapcontainsKey()检查是否包含键
MapcontainsValue()检查是否包含值

2.3 函数方法 ​

方法描述
toString()转换为字符串
call()调用函数对象
runtimeType获取运行时类型

3. 面向对象核心知识点(类、继承、封装、多态) ​

3.1 类的定义 ​

dart
class Person {
  // 属性
  String name;
  int age;
  
  // 构造函数
  Person(this.name, this.age);
  
  // 命名构造函数
  Person.fromBirthYear(String name, int birthYear) {
    this.name = name;
    this.age = DateTime.now().year - birthYear;
  }
  
  // 方法
  void greet() {
    print('Hello, my name is $name');
  }
}

3.2 继承 ​

dart
class Student extends Person {
  String school;
  
  Student(String name, int age, this.school) : super(name, age);
  
  // 重写方法
  @override
  void greet() {
    super.greet();
    print('I study at $school');
  }
}

3.3 封装 ​

dart
class BankAccount {
  double _balance = 0.0; // 私有属性
  
  // getter
  double get balance => _balance;
  
  // setter
  set deposit(double amount) {
    if (amount > 0) {
      _balance += amount;
    }
  }
  
  void withdraw(double amount) {
    if (amount > 0 && amount <= _balance) {
      _balance -= amount;
    }
  }
}

3.4 多态 ​

dart
abstract class Shape {
  void draw();
}

class Circle extends Shape {
  @override
  void draw() {
    print('Drawing a circle');
  }
}

class Rectangle extends Shape {
  @override
  void draw() {
    print('Drawing a rectangle');
  }
}

// 使用多态
void drawShape(Shape shape) {
  shape.draw();
}

3.5 Mixin ​

dart
mixin Swimmable {
  void swim() {
    print('Swimming');
  }
}

mixin Flyable {
  void fly() {
    print('Flying');
  }
}

class Duck with Swimmable, Flyable {
  void quack() {
    print('Quacking');
  }
}

4. 异步编程方法汇总(Future、async/await) ​

4.1 Future 基础 ​

dart
// 创建 Future
Future<String> future = Future.value('Hello');

// 处理 Future
future.then((value) {
  print(value);
}).catchError((error) {
  print('Error: $error');
}).whenComplete(() {
  print('Completed');
});

4.2 async/await ​

dart
// 异步函数
Future<void> fetchData() async {
  try {
    // 模拟网络请求
    await Future.delayed(Duration(seconds: 2));
    print('Data fetched successfully');
  } catch (e) {
    print('Error: $e');
  }
}

// 调用异步函数
void main() async {
  await fetchData();
  print('Main function completed');
}

4.3 Future 组合 ​

dart
// 等待多个 Future 完成
Future<void> fetchMultipleData() async {
  var future1 = Future.delayed(Duration(seconds: 1), () => 'Data 1');
  var future2 = Future.delayed(Duration(seconds: 2), () => 'Data 2');
  
  var results = await Future.wait([future1, future2]);
  print(results); // ['Data 1', 'Data 2']
}

// 任一 Future 完成
Future<void> raceFutures() async {
  var future1 = Future.delayed(Duration(seconds: 2), () => 'Slow');
  var future2 = Future.delayed(Duration(seconds: 1), () => 'Fast');
  
  var result = await Future.any([future1, future2]);
  print(result); // 'Fast'
}

5. 常用代码模板(复制即用,提高开发效率) ​

5.1 基础结构模板 ​

dart
// main.dart
void main() {
  print('Hello, Dart!');
  // 主逻辑
}

5.2 类模板 ​

dart
class ClassName {
  // 属性
  String property1;
  int property2;
  
  // 构造函数
  ClassName(this.property1, this.property2);
  
  // 方法
  void method1() {
    // 实现
  }
  
  // 静态方法
  static void staticMethod() {
    // 实现
  }
}

5.3 异步函数模板 ​

dart
Future<ReturnType> asyncFunction() async {
  try {
    // 异步操作
    await Future.delayed(Duration(seconds: 1));
    return ReturnType();
  } catch (e) {
    print('Error: $e');
    rethrow;
  }
}

5.4 集合处理模板 ​

dart
// 过滤列表
List<T> filterList<T>(List<T> list, bool Function(T) predicate) {
  return list.where(predicate).toList();
}

// 映射列表
List<R> mapList<T, R>(List<T> list, R Function(T) mapper) {
  return list.map(mapper).toList();
}

// 排序列表
void sortList<T>(List<T> list, int Function(T, T) compare) {
  list.sort(compare);
}

5.5 错误处理模板 ​

dart
try {
  // 可能出错的代码
  int result = 10 ~/ 0;
} catch (e) {
  // 捕获异常
  print('Error: $e');
} finally {
  // 无论是否出错都会执行
  print('Operation completed');
}

6. 新手易错点对照表(快速排查问题) ​

错误类型常见表现解决方案
空安全错误变量未初始化、空值调用方法使用 null 检查、?. 运算符、?? 运算符
函数参数错误可选参数与必选参数混淆明确参数类型,使用命名参数提高可读性
异步代码错误await 使用不当、执行顺序错误正确使用 async/await,理解 Future 链
继承错误super 关键字使用遗漏重写方法时正确调用 super 方法
库导入错误路径错误、第三方库安装失败检查 pubspec.yaml,使用正确的导入路径
类型错误类型不匹配、隐式类型转换明确类型声明,使用类型检查
作用域错误变量作用域混淆了解 Dart 变量作用域规则
集合操作错误索引越界、修改不可变集合使用安全的集合操作,检查边界条件

7. 常用第三方库推荐(按场景分类) ​

7.1 网络请求 ​

库名描述用途
dio强大的 HTTP 客户端网络请求、文件上传下载
http官方 HTTP 客户端简单网络请求
chopper基于 Retrofit 的 HTTP 客户端RESTful API 调用

7.2 状态管理 ​

库名描述用途
provider简单的状态管理中小型应用状态管理
riverpod改进的状态管理更灵活的状态管理方案
bloc基于流的状态管理复杂应用状态管理

7.3 数据存储 ​

库名描述用途
shared_preferences键值对存储简单数据持久化
sqfliteSQLite 数据库本地数据库存储
hive轻量级 NoSQL 数据库快速数据存储

7.4 序列化 ​

库名描述用途
json_serializableJSON 序列化生成器自动生成 JSON 序列化代码
freezed不可变类生成器生成不可变数据类

7.5 工具库 ​

库名描述用途
path路径操作文件路径处理
intl国际化和本地化日期时间格式化、本地化
crypto加密库哈希函数、加密操作

7.6 UI 相关(Flutter) ​

库名描述用途
flutter_svgSVG 支持显示 SVG 图像
cached_network_image网络图片缓存高效加载网络图片
flutter_blocFlutter BLoC 实现Flutter 状态管理

7.7 测试 ​

库名描述用途
test单元测试框架编写单元测试
mockito模拟库测试中模拟依赖
flutter_testFlutter 测试框架Flutter 组件测试

© 2026 编程马·菜鸟教程 版权所有