flutter架 构项目基础

This commit is contained in:
崔宝新
2026-09-04 15:22:20 +08:00
parent 70967229d0
commit 0c5aee59c0
265 changed files with 35484 additions and 0 deletions
+71
View File
@@ -0,0 +1,71 @@
# build_runner 代码生成指南
## 一、是什么
`build_runner` 是 Dart 官方的**代码生成调度器**。它本身不生成任何代码,而是统一调度各个**生成器插件**,根据模型上的注解自动生成 `.g.dart` 文件。
类比:`build_runner` = 工厂流水线调度员,各个生成器插件 = 流水线上的工人。
## 二、当前项目的生成器
| 生成器插件 | 注解 | 生成内容 | 状态 |
|---|---|---|---|
| `isar_community_generator` | `@collection` | Isar 数据库 Schema(增删改查) | ✅ 已配置 |
| `json_serializable` | `@JsonSerializable()` | `fromJson` / `toJson` 方法 | 🔲 待添加 |
一次 `build_runner build` 会**同时调度所有已配置的生成器**,全部 `.g.dart` 一次性生成。
## 三、涉及的模型文件
### Isar 模型(`@collection`)
| 文件 | 说明 |
|---|---|
| `lib/core/storage/models/question.dart` | 题目 |
| `lib/core/storage/models/wrong_question.dart` | 错题 |
| `lib/core/storage/models/answer_record.dart` | 答题记录 |
| `lib/core/storage/models/play_record.dart` | 播放记录 |
| `lib/core/version/app_version_entity.dart` | 版本信息实体 |
### json_serializable 模型(`@JsonSerializable`)
> 待引入后,纯接口 DTO 模型(如 `UserPointRecord`、`OssStsConfig` 等)将使用注解自动生成序列化代码,替代手写 `fromJson`。
## 四、使用命令
```bash
# 生成一次(推荐日常使用)
dart run build_runner build
# 清理旧产物后重新生成(遇到生成代码冲突时使用)
dart run build_runner build --delete-conflicting-outputs
# 监听模式:每次保存文件自动生成(开发阶段推荐)
dart run build_runner watch
```
## 五、什么时候需要跑
| 操作 | 是否需要跑 |
|---|---|
| Isar 模型加了/删了/改了字段 | ✅ 必须,否则编译报错 |
| `@JsonSerializable` 模型改了字段 | ✅ 必须,否则序列化字段对不上 |
| 只改了页面 UI / 业务逻辑 | ❌ 不需要 |
| 只改了 `pubspec.yaml` 依赖 | ❌ 不需要(跑 `flutter pub get` 即可) |
## 六、生成产物说明
- 生成文件命名:`xxx.g.dart`,和模型文件同目录
- 生成文件**必须提交到 Git**(`.gitignore` 里不要排除 `*.g.dart`)
- **不要手动编辑** `.g.dart` 文件,改了也会被下次生成覆盖
## 七、常见问题
### Q: 编译报错 `MissingStubError` 或 `is not a subtype of`
A: 模型字段改了但没跑 build_runner,重新生成即可。
### Q: 报 `AlreadyExistsException` 或 conflicting outputs
A: 加 `--delete-conflicting-outputs` 参数清理后重新生成。
### Q: 生成很慢怎么办
A: 开发阶段用 `watch` 模式,增量生成比每次全量 `build` 快很多。