Appearance
附录: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'); // true1.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 数据类型方法
| 类型 | 常用方法 | 描述 |
|---|---|---|
| String | length | 获取字符串长度 |
| String | isEmpty | 检查是否为空 |
| String | contains() | 检查是否包含子字符串 |
| String | split() | 分割字符串 |
| String | trim() | 去除首尾空白 |
| int | toString() | 转换为字符串 |
| int | toDouble() | 转换为double |
| double | toStringAsFixed() | 保留指定位数小数 |
| bool | toString() | 转换为字符串 |
2.2 集合方法
| 集合 | 常用方法 | 描述 |
|---|---|---|
| List | add() | 添加元素 |
| List | remove() | 移除元素 |
| List | length | 获取长度 |
| List | isEmpty | 检查是否为空 |
| List | contains() | 检查是否包含元素 |
| List | sort() | 排序 |
| List | map() | 映射转换 |
| List | where() | 过滤元素 |
| Set | add() | 添加元素 |
| Set | remove() | 移除元素 |
| Set | contains() | 检查是否包含元素 |
| Set | union() | 合并集合 |
| Map | putIfAbsent() | 不存在时添加 |
| Map | remove() | 移除键值对 |
| Map | containsKey() | 检查是否包含键 |
| Map | containsValue() | 检查是否包含值 |
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 | 键值对存储 | 简单数据持久化 |
| sqflite | SQLite 数据库 | 本地数据库存储 |
| hive | 轻量级 NoSQL 数据库 | 快速数据存储 |
7.4 序列化
| 库名 | 描述 | 用途 |
|---|---|---|
| json_serializable | JSON 序列化生成器 | 自动生成 JSON 序列化代码 |
| freezed | 不可变类生成器 | 生成不可变数据类 |
7.5 工具库
| 库名 | 描述 | 用途 |
|---|---|---|
| path | 路径操作 | 文件路径处理 |
| intl | 国际化和本地化 | 日期时间格式化、本地化 |
| crypto | 加密库 | 哈希函数、加密操作 |
7.6 UI 相关(Flutter)
| 库名 | 描述 | 用途 |
|---|---|---|
| flutter_svg | SVG 支持 | 显示 SVG 图像 |
| cached_network_image | 网络图片缓存 | 高效加载网络图片 |
| flutter_bloc | Flutter BLoC 实现 | Flutter 状态管理 |
7.7 测试
| 库名 | 描述 | 用途 |
|---|---|---|
| test | 单元测试框架 | 编写单元测试 |
| mockito | 模拟库 | 测试中模拟依赖 |
| flutter_test | Flutter 测试框架 | Flutter 组件测试 |
