Flutter 架构模式
"架构"不是炫技,是给团队和未来的自己定规矩:数据从哪来、业务在哪写、UI 在哪渲染、错误在哪处理。
写不写架构看项目规模,小项目反而有害(你只是在画格子)。
一、什么时候需要架构?
| 项目规模 | 推荐 |
|---|---|
| Demo / 学习 | 无架构,扁平结构 |
| 1~3 个页面 | StatefulWidget + Service 类 |
| 5~10 个页面 | Cubit + Repository 简化分层 |
| 10+ 页面 / 团队 | Clean Architecture / 类似 |
| 大型 / 长期维护 | Clean Arch + DDD + 严格分层 |
二、最小可用架构(2 层)
UI(StatefulWidget / Cubit) → Service(Dio + 业务方法)class TodoService {
final Dio dio;
TodoService(this.dio);
Future<List<Todo>> getAll() async {
final r = await dio.get('/todos');
return (r.data as List).map((e) => Todo.fromJson(e)).toList();
}
}
class TodoCubit extends Cubit<List<Todo>> {
final TodoService service;
TodoCubit(this.service) : super([]);
Future<void> load() async => emit(await service.getAll());
}够用 80% 中小项目。
三、Clean Architecture(干净架构)
由 Robert C. Martin 提出。核心是依赖方向:外层依赖内层,内层不知道外层。
经典三层
┌──────────────────────────────────────┐
│ Presentation(UI、Cubit、Bloc) │ 外层
│ │ │
│ ↓ 调用 │
├──────────────────────────────────────┤
│ Domain(实体、UseCase、Repo 接口) │ ← 核心,不依赖任何外部
│ ↑ 实现 │
├──────────────────────────────────────┤
│ Data(API、DB、Repo 实现) │ 外层
└──────────────────────────────────────┘关键:Domain 是唯一稳定的中心,Presentation 和 Data 都依赖它,而它谁也不依赖。
各层职责
Domain(领域层 — 业务规则)
不依赖 Flutter、Dio、Drift,纯 Dart。
// 实体
class Todo {
final String id;
final String title;
final bool done;
Todo({required this.id, required this.title, this.done = false});
}
// Repository 接口(纯抽象)
abstract class TodoRepository {
Future<List<Todo>> getAll();
Future<void> add(Todo t);
}
// UseCase(一个业务动作)
class GetTodos {
final TodoRepository repo;
GetTodos(this.repo);
Future<List<Todo>> call() => repo.getAll();
}
class AddTodo {
final TodoRepository repo;
AddTodo(this.repo);
Future<void> call(String title) {
if (title.trim().isEmpty) throw ArgumentError('标题不能为空');
return repo.add(Todo(id: _uuid(), title: title));
}
}UseCase 把"业务规则"显式化:一个动作 = 一个类。规则(标题不能空)写在这里,不写在 UI 也不写在 API 层。
Data(数据层 — 实现细节)
class TodoApi {
final Dio dio;
TodoApi(this.dio);
Future<List<TodoDto>> getAll() async {
final r = await dio.get('/todos');
return (r.data as List).map((e) => TodoDto.fromJson(e)).toList();
}
}
class TodoDto {
final String id;
final String title;
final bool done;
TodoDto({required this.id, required this.title, required this.done});
factory TodoDto.fromJson(Map j) =>
TodoDto(id: j['id'], title: j['title'], done: j['done']);
// 转成 Domain 层的 Todo
Todo toEntity() => Todo(id: id, title: title, done: done);
}
// 实现 Domain 层的接口
class TodoRepoImpl implements TodoRepository {
final TodoApi api;
final TodoLocalDb localDb;
TodoRepoImpl(this.api, this.localDb);
@override
Future<List<Todo>> getAll() async {
try {
final list = await api.getAll();
await localDb.cache(list);
return list.map((e) => e.toEntity()).toList();
} on DioException {
// 降级到本地缓存
return (await localDb.getAll()).map((e) => e.toEntity()).toList();
}
}
}DTO(Data Transfer Object)和 Entity 分开:DTO 跟 API 字段一致,Entity 是业务概念。API 改了字段不会影响 Domain。
Presentation(展示层)
class TodoCubit extends Cubit<TodoState> {
final GetTodos getTodos;
final AddTodo addTodo;
TodoCubit(this.getTodos, this.addTodo) : super(TodoState.initial());
Future<void> load() async {
emit(state.copyWith(loading: true));
final todos = await getTodos();
emit(state.copyWith(loading: false, todos: todos));
}
Future<void> add(String title) async {
await addTodo(title);
await load();
}
}Cubit 只调 UseCase,不直接调 Repository。UseCase 单一职责,改业务规则只动它。
文件结构
lib/
├── core/ 通用(网络、错误、工具)
├── features/
│ └── todo/
│ ├── domain/
│ │ ├── entities/todo.dart
│ │ ├── repositories/todo_repository.dart
│ │ └── usecases/
│ │ ├── get_todos.dart
│ │ └── add_todo.dart
│ ├── data/
│ │ ├── models/todo_dto.dart
│ │ ├── datasources/todo_api.dart
│ │ └── repositories/todo_repo_impl.dart
│ └── presentation/
│ ├── cubit/
│ ├── pages/
│ └── widgets/
└── injection.dart ← 依赖注入(get_it)四、Feature-first vs Layer-first
# Feature-first(推荐)
lib/features/auth/
lib/features/todo/
lib/features/profile/
# Layer-first
lib/data/
lib/domain/
lib/presentation/Feature-first 更适合中大型项目:
- 新人接手只看一个 feature 文件夹就能改
- 删功能时直接删一整个文件夹
- 重构跨 feature 影响小
Layer-first 适合功能少但层多的项目(后端代码常用)。
五、UseCase 是不是过度设计?
简单 CRUD 直接在 Repo 里就行,不必每个动作都包一个 UseCase。
UseCase 价值在于:
- 业务规则复杂(
AddTodo验证标题、扣积分、发通知 — 三步合一) - 多个动作组合(
Checkout= 校验购物车 + 锁库存 + 创建订单 + 调支付) - 多端复用(同一个 UseCase 给 App / Web / 桌面用)
轻量替代:Repo 里写业务方法,Cubit 直接调:
class TodoCubit extends Cubit<TodoState> {
final TodoRepository repo;
TodoCubit(this.repo) : super(TodoState.initial());
Future<void> add(String title) async {
if (title.trim().isEmpty) {
emit(state.copyWith(error: '标题不能为空'));
return;
}
await repo.add(Todo(id: _uuid(), title: title));
await load();
}
}判断标准:这一段业务逻辑会被多个 Cubit 复用吗?如果不会,直接写在 Cubit 里。
六、MVVM(常见替代)
View(Widget) ↔ ViewModel(状态 + 命令) → Model(数据)Flutter 里 ViewModel ≈ ChangeNotifier / Cubit / Notifier。
class TodoViewModel extends ChangeNotifier {
final TodoRepository repo;
TodoViewModel(this.repo);
List<Todo> _todos = [];
bool _loading = false;
List<Todo> get todos => _todos;
bool get loading => _loading;
Future<void> load() async {
_loading = true; notifyListeners();
_todos = await repo.getAll();
_loading = false; notifyListeners();
}
}Flutter 里 MVVM 和 Bloc 写法很像,区别只在风格。
七、DDD(领域驱动设计)
DDD 关心怎么把业务概念正确建模,不是文件结构。
几个核心概念
1. Entity vs ValueObject
- Entity:有 id,生命周期长(
User、Order) - ValueObject:无 id,值相等就算同一个(
Money、Address)
class Money {
final int cents;
final String currency;
const Money(this.cents, this.currency);
Money operator +(Money o) {
if (currency != o.currency) throw 'currency mismatch';
return Money(cents + o.cents, currency);
}
@override
bool operator ==(Object o) =>
o is Money && o.cents == cents && o.currency == currency;
@override
int get hashCode => Object.hash(cents, currency);
}2. Aggregate(聚合根)
一组实体的"管理者"。所有外界修改必须经过它。
class Order { // 聚合根
final String id;
final List<OrderLine> lines;
Money _total;
void addLine(Product p, int qty) {
if (_locked) throw '订单已锁定';
lines.add(OrderLine(p, qty));
_total += p.price * qty;
}
}外界只调 order.addLine(...),不直接 order.lines.add(...)。所有不变量(total、状态机)都在聚合根里维护。
3. Domain Event
业务发生了什么(OrderPlaced、PaymentReceived),用事件解耦各模块。
4. Bounded Context(限界上下文)
一个 User 在登录上下文里只关心 id+token,在订单上下文里关心地址+联系电话——不要做一个无所不能的 User 类,按上下文拆。
DDD 适合业务很复杂的领域(电商、金融、ERP)。简单 App 别上,反而臃肿。
八、不同状态管理对应的架构
| 状态管理 | 推荐架构 |
|---|---|
| setState | 无架构 / 简单 Service |
| Provider / GetX | 简化分层(Cubit + Repo) |
| Riverpod | Repo + Notifier(可选 UseCase) |
| Bloc | Clean Architecture 经典搭配 |
Bloc + Clean Architecture 是 Flutter 社区的"权威搭配"(看 Reso Coder 的教程)。
九、错误处理:Result 类型
返回 Future<Either<Failure, T>> 替代抛异常,让"成功/失败"显式:
dependencies:
fpdart: ^1.1.0 # 或 dartzabstract class Failure {
final String message;
Failure(this.message);
}
class NetworkFailure extends Failure { NetworkFailure() : super('网络错误'); }
class ServerFailure extends Failure { ServerFailure(super.m); }
Future<Either<Failure, List<Todo>>> getAll() async {
try {
final list = await api.getAll();
return Right(list.map((e) => e.toEntity()).toList());
} on DioException catch (e) {
return Left(NetworkFailure());
}
}
// 调用方
final result = await repo.getAll();
result.fold(
(failure) => emit(state.copyWith(error: failure.message)),
(todos) => emit(state.copyWith(todos: todos)),
);好处:编译器强制你处理失败,不会忘。 缺点:写起来啰嗦,初学者难。
如果团队不接受,直接抛业务异常 + 全局 try-catch 也行。
十、依赖注入与架构
回顾 11:
// 接口在 domain
abstract class TodoRepository { ... }
// 实现在 data
class TodoRepoImpl implements TodoRepository { ... }
// 注册(injection.dart)
getIt.registerLazySingleton<TodoRepository>(
() => TodoRepoImpl(getIt(), getIt()),
);
// UseCase 拿到的是接口,不是实现
final getTodos = GetTodos(getIt<TodoRepository>());任何层都通过接口拿依赖。测试时一行 override 就替换。
十一、不要犯的错
1. 接口没必要也包
// ❌ 单实现的接口纯属浪费
abstract class FooService { void foo(); }
class FooServiceImpl implements FooService { ... }只有"有 mock 需要"或"未来可能多实现"才包接口。Repository 大概率要,Service 不一定。
2. UseCase 只是包了一层 Repo
class GetUser {
final UserRepo repo;
Future<User> call(String id) => repo.getUser(id); // ❌ 完全没业务
}→ 没价值,直接在 Cubit 里调 Repo。
3. Cubit 里写网络请求
class TodoCubit extends Cubit<...> {
Future<void> load() async {
final r = await dio.get('/todos'); // ❌ 跨层了
...
}
}→ 网络细节属于 Data 层,Cubit 永远只调 Repo / UseCase。
4. Domain 层 import flutter
// domain/usecases/get_todos.dart
import 'package:flutter/material.dart'; // ❌→ Domain 必须纯 Dart,不依赖 Flutter。这样未来移到服务端、命令行、桌面都能复用。
5. 每个文件都要分层
小项目 5 个 todo 也搞 3 层 5 文件 → 过度。架构是手段,不是目的。
十二、推荐组合
简单(< 5 页)
StatefulWidget / Cubit + Service 类中型(5~15 页)
Bloc/Riverpod + Repository + DTO/Entity 区分
get_it 做 DI大型(15+ 页 / 多人 / 长期维护)
Clean Architecture 三层
+ injectable + get_it
+ UseCase
+ Either / Result 错误处理
+ Feature-first 文件夹十三、和已学知识的串联
- Bloc / Riverpod(09 / 10)是 Presentation 层的天然选择
- Repository 配合 Drift / Hive(14)做本地缓存,Dio(13)做远程
- DI(11)让接口和实现分离,这是 Clean Architecture 的根基
- 测试(20)的所有"mock 一层"都是 Clean Arch 的红利
- 路由(12)归 Presentation,UseCase 不知道有路由
十四、心智模型
"架构 = 给依赖方向定规矩"
UI → 调 → Cubit / Bloc
Cubit → 调 → UseCase(可选)
UseCase → 调 → Repository(接口)
Repository → 实现层调 → API / DB
依赖方向只能从外往内,内层不知道外层判断架构对不对的简单标准:
- 改 UI 文案 → 不动业务逻辑
- 换网络库 Dio → http → UI 一行不动
- 测 Cubit → 不需要真发请求
- 新人看一个 feature → 在一个文件夹里就能找全
满足这些,你的架构就够好了。