flutter-architecture
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseFlutter Architecture
Flutter 架构
Structure every Flutter app as a layered, feature-first MVVM system, sized to the app. You must
always answer "where does this code belong?" in one second. Based on Flutter's official Guide to app
architecture, with Riverpod 3.x as the one mechanism for both state and dependency injection.
Two failure modes kill an architecture: under-structure (a widget touching a database) and
over-structure (a wrapping one repository call, an interface over code that already runs in
a test). This skill fights both. Start small; add a layer only when it carries a load you can name.
*UseCaseRead the reference for the task at hand:
- — the layer model, folder-vs-package continuum, the DAG, barrels, feature-folder anatomy, and the "when multi-package (workspace)" note.
references/module-and-layers.md - — the reject-over-engineering table, "abstract only what you can't test", and how architecture scales with app size.
references/right-sizing.md - — provider graph, keepAlive vs autoDispose, placeholder-override composition root, isolate-safe factories,
references/state-di-riverpod.mdtests.ProviderContainer
Run before opening a PR.
scripts/check_architecture.sh将每个 Flutter 应用组织为与规模相适配的分层、功能优先 MVVM 系统。你必须始终能在一秒内回答“这段代码应该放在哪里?”。本指南基于 Flutter 官方《应用架构指南》,并使用 Riverpod 3.x 作为状态管理与依赖注入的唯一机制。
两种失败模式会毁掉架构:结构不足(widget 直接访问数据库)和结构过度(用一个 包装一次 repository 调用,或为已经能在测试中运行的代码添加 interface)。本 skill 同时防范这两种问题。从小处开始;只有当新增一层承载了你能明确说明的职责时,才添加这一层。
*UseCase针对当前任务阅读参考资料:
- ——层级模型、文件夹与 package 的连续谱、DAG、barrel、feature 文件夹结构,以及“何时使用多 package(workspace)”的说明。
references/module-and-layers.md - ——拒绝过度设计的对照表、“只抽象无法测试的部分”,以及架构如何随应用规模扩展。
references/right-sizing.md - ——provider graph、keepAlive 与 autoDispose、placeholder override composition root、isolate-safe factory、
references/state-di-riverpod.md测试。ProviderContainer
开启 PR 前运行 。
scripts/check_architecture.shNon-negotiable rules
不可妥协的规则
- Answer "where does this belong?" in one second. Group by feature first, layer second. No
giant app-wide ,
screens/, ormodels/bucket — those smear one feature across the tree and force a name lookup on every edit.widgets/ - Two layers minimum: UI and Data. A domain/use-case layer only when logic spans multiple
repositories (projection, aggregation, a multi-step workflow). A that forwards one repository call is a rename, not a boundary — Flutter's own guidance rates the domain layer conditional and says most apps don't need it.
*UseCase - Abstract exactly what cannot run in a test — name what the abstraction makes testable. A
platform channel, network client, or plugin that can't execute in earns an interface + a fake. Code that already runs headless (an in-memory DB, a pure calculator, a repository over it) stays concrete. "It's cleaner" is not a load; if you can't name the seam it buys, don't add it.
flutter test - Data flows one way; never skip or reverse a hop. Data down: . Events up:
Service → Repository → ViewModel → View. A widget calls its ViewModel only; a ViewModel calls repositories only. No two-way binding, no widget reaching a data source.View → ViewModel → Repository - The View is dumb. A View does layout, /
ifon state, animation, and navigation — nothing else. No business logic, no formatting/number math, noswitch, no data access. If a widget computes or fetches, it's in the wrong layer.try/catch - One ViewModel per feature, over immutable state. The ViewModel holds private mutable state
and exposes intent methods (,
load()); every transition assigns a new immutable value with value equality. No public setters, no mutable field the UI edits in place.add(...) - Repositories are the single source of truth AND the single write path. Every mutation is one named repository method that persists first, then publishes (one transaction where the store supports it). Never persist-after-publish — a crash in between credits state that never saved.
- Derive, don't store. Counts, totals, streaks, filtered lists are computed from the source of truth (a stream/derived provider), never a second stored counter that can drift out of sync.
- Map at the boundary; keep domain types out of the edges. Repositories map storage rows / JSON
DTOs → immutable domain value objects. A generated Drift row or a never reaches a ViewModel or widget; unit math and locale formatting never happen in a widget.
Map - Inject through providers; depend on the abstraction where it earns one. No globals, no
singletons, no service locator reached from a widget, no outside an injected
DateTime.now(). A composition root wires the object graph once.Clock - Features are FOLDERS; foundations become PACKAGES only when a compile wall is load-bearing. Default to a single package. A feature never imports another feature — share via a foundation layer or navigate by route ID. The dependency graph is a strict downward-only DAG.
- Errors are typed values at boundaries. Repositories/use-cases return a sealed /
Resultrather than throwing across a layer; the UI switches exhaustively. SeeFailure.error-handling-typed-results
- **在一秒内回答“它应该放在哪里?”**首先按 feature 划分,再按 layer 划分。不要建立应用级的巨大 、
screens/或models/目录;这种结构会把同一个 feature 分散到目录树中,导致每次修改都要查找名称。widgets/ - 至少两层:UI 和 Data。仅当逻辑跨越多个 repository 时,才添加 domain/use-case 层(投影、聚合、多步骤工作流)。仅转发一次 repository 调用的 只是改名,并非真正的边界——Flutter 官方指南将 domain 层视为条件性设计,并指出大多数应用都不需要它。
*UseCase - 只抽象那些确实无法在测试中运行的部分——并明确说明该抽象使什么变得可测试。无法在 中执行的 platform channel、network client 或 plugin 才值得拥有 interface + fake。已经在 headless 环境运行的代码(in-memory DB、pure calculator、基于其实现的 repository)应保持具体。“更整洁”不是有效职责;如果无法说明它带来的测试接缝,就不要添加。
flutter test - **数据只能单向流动;绝不能跳过或反向跨越任何一层。**数据向下:。事件向上:
Service → Repository → ViewModel → View。widget 只能调用自己的 ViewModel;ViewModel 只能调用 repository。禁止双向绑定,禁止 widget 直接访问数据源。View → ViewModel → Repository - **View 是 dumb 的。**View 只负责布局、基于状态执行 /
if、动画和导航——不做其他事情。不允许业务逻辑、格式化/数值计算、switch或数据访问。如果 widget 执行计算或获取数据,就说明它位于错误的层。try/catch - 每个 feature 使用一个基于不可变状态的 ViewModel。ViewModel 持有私有可变状态,并公开意图方法(、
load());每次状态转换都赋值一个具有值相等性的新不可变值。不允许公共 setter,也不允许 UI 原地修改可变字段。add(...) - Repository 既是单一事实来源,也是单一写入路径。每次 mutation 都通过一个有明确名称的 repository 方法完成,并且先持久化,再发布(存储支持时使用一个 transaction)。绝不能先发布后持久化——两者之间发生崩溃会让实际未保存的状态生效。
- 派生,不要存储。计数、总计、连续天数、筛选列表应从事实来源计算(通过 stream/derived provider),绝不能保存可能失去同步的第二个计数器。
- 在边界处映射;领域类型不得进入外部层。Repository 将存储行/JSON DTO 映射为不可变的领域值对象。生成的 Drift row 或 绝不能到达 ViewModel 或 widget;单位换算和 locale 格式化绝不能发生在 widget 中。
Map - **通过 provider 注入;在真正值得抽象的地方依赖抽象。**禁止 globals、singletons,禁止 widget 访问 service locator,禁止在注入的 之外使用
Clock。composition root 只组装一次对象图。DateTime.now() - Feature 是 FOLDER;只有当编译期边界具有承重作用时,基础层才成为 PACKAGE。默认采用单一 package。一个 feature 绝不导入另一个 feature——应通过基础层共享,或按 route ID 导航。依赖图必须是严格只向下的 DAG。
- **错误在边界处以类型化值表示。**Repository/use-case 返回 sealed /
Result,而不是跨层抛出异常;UI 对其进行穷尽式 switch。参见Failure。error-handling-typed-results
The layered shape (single package, the default)
分层结构(单一 package,默认)
project-structure-and-packageslib/features/presentation/text
lib/
main.dart # thin entrypoint → bootstrap()
bootstrap.dart # composition root: build infra, override placeholder providers, runApp
app.dart # MaterialApp.router, theme, top-level ProviderScope children
core/ # PURE foundation, NO Flutter: value objects, Result/Failure, the Clock seam,
# extensions, pure calculators (the sanctioned foundation, not a junk-drawer)
data/ # shared data layer: Drift db, DAOs, repositories, row→model mappers
services/ # injectable side-effect ports + live impls (services/native/ = MethodChannel)
routing/ # the single go_router config, typed routes, guards
theme/ l10n/ # ThemeExtension token sets; generated AppLocalizations + ARB
features/
tasks/
presentation/
task_list_screen.dart # View: dumb ConsumerWidget
task_list_notifier.dart # ViewModel: StreamNotifier over immutable state
widgets/ # widget CLASSES used only by this feature
application/ # optional: use-cases, ONLY when logic spans repositories
domain/ # optional: feature-local models
# data/ usually ABSENT — features read shared repos from lib/data/Rules of thumb: depends on nothing above it and stays free of ; has no
Flutter UI imports; a feature depends on //, never on a sibling feature. Add a
feature-local + (use-cases) folder only when logic spans repositories.
core/BuildContextdata/coredataservicesdomain/application/project-structure-and-packageslib/features/presentation/text
lib/
main.dart # thin entrypoint → bootstrap()
bootstrap.dart # composition root: build infra, override placeholder providers, runApp
app.dart # MaterialApp.router, theme, top-level ProviderScope children
core/ # PURE foundation, NO Flutter: value objects, Result/Failure, the Clock seam,
# extensions, pure calculators (the sanctioned foundation, not a junk-drawer)
data/ # shared data layer: Drift db, DAOs, repositories, row→model mappers
services/ # injectable side-effect ports + live impls (services/native/ = MethodChannel)
routing/ # the single go_router config, typed routes, guards
theme/ l10n/ # ThemeExtension token sets; generated AppLocalizations + ARB
features/
tasks/
presentation/
task_list_screen.dart # View: dumb ConsumerWidget
task_list_notifier.dart # ViewModel: StreamNotifier over immutable state
widgets/ # widget CLASSES used only by this feature
application/ # optional: use-cases, ONLY when logic spans repositories
domain/ # optional: feature-local models
# data/ usually ABSENT — features read shared repos from lib/data/经验法则: 不依赖其上任何层,并保持不包含 ; 不导入 Flutter UI;一个 feature 可以依赖 //,但绝不依赖同级 feature。仅当逻辑跨越多个 repository 时,才添加 feature 内的 + (use-case)目录。
core/BuildContextdata/coredataservicesdomain/application/The feature slice (Riverpod-first "how")
Feature 切片(Riverpod 优先的“实现方式”)
A dumb View reads one ViewModel; the ViewModel holds private state and exposes intent methods.
dart
// features/tasks/presentation/task_list_notifier.dart — the ViewModel.
// build() returns the live repository stream; a mutation commits through the single write
// path and the watched stream RE-EMITS. No manual `state = ...` republish.
final class TaskListNotifier extends StreamNotifier<List<Task>> {
Stream<List<Task>> build() {
ref.onDispose(() {/* controllers/subscriptions released here */});
return ref.watch(taskRepositoryProvider).watchTasks(); // track every emission
}
Future<void> add(String title) async { // intent method — no setter
final id = ref.read(idGeneratorProvider)(); // injected id source — never a UI UniqueKey
await ref.read(taskRepositoryProvider).add(Task.create(id: id, title: title));
// No republish: the committed write makes watchTasks() re-emit and build()'s stream updates state.
}
}
final taskListNotifierProvider =
StreamNotifierProvider<TaskListNotifier, List<Task>>(TaskListNotifier.new);The repository behind it is the single source of truth AND single write path — a
stream plus an that persists first, then the stream re-emits. Give it an
only when the real impl can't run in a test (rule 3); over an in-memory DB a concrete class is fine.
watchTasks()add()abstract interfacedart
// features/tasks/task_list_screen.dart — the View is dumb: read one provider, render.
final class TaskListScreen extends ConsumerWidget {
const TaskListScreen({super.key});
Widget build(BuildContext context, WidgetRef ref) {
final tasks = ref.watch(taskListNotifierProvider);
return tasks.when(
loading: () => const Center(child: CircularProgressIndicator()),
error: (e, _) => ErrorView(onRetry: () => ref.invalidate(taskListNotifierProvider)),
data: (list) => ListView(
children: [for (final t in list) TaskTile(task: t)], // widget CLASS, not a _buildTile()
),
);
}
}Providers ARE the dependency injection. Wire deps via , key per-entity state with ,
and use for per-screen controllers. See for the full API
discipline (watch/read/listen split, , stale-closure hazards).
ref.watchfamilyautoDisposestate-management-riverpod.select一个纯展示 View 读取一个 ViewModel;ViewModel 持有私有状态并公开意图方法。
dart
// features/tasks/presentation/task_list_notifier.dart — the ViewModel.
// build() returns the live repository stream; a mutation commits through the single write
// path and the watched stream RE-EMITS. No manual `state = ...` republish.
final class TaskListNotifier extends StreamNotifier<List<Task>> {
Stream<List<Task>> build() {
ref.onDispose(() {/* controllers/subscriptions released here */});
return ref.watch(taskRepositoryProvider).watchTasks(); // track every emission
}
Future<void> add(String title) async { // intent method — no setter
final id = ref.read(idGeneratorProvider)(); // injected id source — never a UI UniqueKey
await ref.read(taskRepositoryProvider).add(Task.create(id: id, title: title));
// No republish: the committed write makes watchTasks() re-emit and build()'s stream updates state.
}
}
final taskListNotifierProvider =
StreamNotifierProvider<TaskListNotifier, List<Task>>(TaskListNotifier.new);其背后的 repository 既是单一事实来源,也是单一写入路径——包含一个 stream,以及负责先持久化、随后由 stream 重新发出数据的 。只有在真实实现无法在测试中运行时,才为它定义 (规则 3);对于 in-memory DB,使用具体类即可。
watchTasks()add()abstract interfacedart
// features/tasks/task_list_screen.dart — the View is dumb: read one provider, render.
final class TaskListScreen extends ConsumerWidget {
const TaskListScreen({super.key});
Widget build(BuildContext context, WidgetRef ref) {
final tasks = ref.watch(taskListNotifierProvider);
return tasks.when(
loading: () => const Center(child: CircularProgressIndicator()),
error: (e, _) => ErrorView(onRetry: () => ref.invalidate(taskListNotifierProvider)),
data: (list) => ListView(
children: [for (final t in list) TaskTile(task: t)], // widget CLASS, not a _buildTile()
),
);
}
}Provider 就是依赖注入。通过 绑定依赖,以 按实体划分状态,并对屏幕级 controller 使用 。完整的 API 规范参见 (watch/read/listen 区分、、stale-closure 隐患)。
ref.watchfamilyautoDisposestate-management-riverpod.selectThe composition root (single write of the object graph)
Composition root(对象图只组装一次)
Infra that constructs asynchronously (a database, dirs, a key store) is injected via placeholder
providers that throw until overridden in — the same seam tests use.
bootstrap.dartdart
// data/providers.dart — placeholder: throws until bootstrap() overrides it (and every test overrides it).
final appDatabaseProvider =
Provider<AppDatabase>((ref) => throw UnimplementedError('override in bootstrap()'));
// bootstrap.dart — the ONE place async infra is built and the graph is composed.
Future<void> bootstrap() async {
WidgetsFlutterBinding.ensureInitialized();
final db = await openAppDatabase(); // plain top-level factory, no BuildContext
runApp(ProviderScope(
overrides: [appDatabaseProvider.overrideWithValue(db)],
child: const App(),
));
}Keep infra (DB, repositories, clock) ; never a singleton that can be torn
down mid-operation. See for main() ordering and error handlers.
keepAliveautoDisposeapp-startup-and-bootstrap异步构建的基础设施(数据库、目录、key store)通过 placeholder provider 注入;这些 provider 在被覆盖前直接抛出异常,并统一在 中覆盖——测试也复用同一接缝。
bootstrap.dartdart
// data/providers.dart — placeholder: throws until bootstrap() overrides it (and every test overrides it).
final appDatabaseProvider =
Provider<AppDatabase>((ref) => throw UnimplementedError('override in bootstrap()'));
// bootstrap.dart — the ONE place async infra is built and the graph is composed.
Future<void> bootstrap() async {
WidgetsFlutterBinding.ensureInitialized();
final db = await openAppDatabase(); // plain top-level factory, no BuildContext
runApp(ProviderScope(
overrides: [appDatabaseProvider.overrideWithValue(db)],
child: const App(),
));
}保持基础设施(DB、repository、clock)为 ;绝不能 一个可能在操作执行中途被销毁的 singleton。 的顺序和错误 handler 参见 。
keepAliveautoDisposemain()app-startup-and-bootstrapRight-sizing: folder vs package, and what to abstract
合理规模:folder 还是 package,以及应该抽象什么
Scale the architecture to the app. The three questions, in order:
- Does this need a new folder or a new file? Almost always a file in an existing feature/layer.
- Does this need a domain/use-case layer? Only if logic spans multiple repositories. One-repo CRUD does not.
- Does this need an interface? Only if the real implementation can't run in , or you genuinely swap dev/prod impls. Name the fake it enables.
flutter test - Does this need a separate package? Only when a compile-time wall is load-bearing — divergence
would be a correctness bug (canonical units/money math, the whole data layer, a scheduler). See the
reject-over-engineering table in .
references/right-sizing.md
When multi-package (workspace). A large app (many teams, a pure-Dart core you golden-test, a reusable design system) may split foundations into packages under a Dart pub workspace. Then: each member setswith one rootresolution: workspace; each package exposes one barrel (pubspec.lock) over a privatecore.dart— never import another package'ssrc/; the pure-Dartsrc/package declares nocoredependency so a stray import is a compile error; the DAG stays acyclic (flutter→ nothing internal; everything →core; the app shell → all). This is an option a big app grows into, never a requirement for a small one — a single package with folders is the default.core
根据应用规模调整架构。依次回答三个问题:
- **需要新增 folder 还是 file?**通常只需在现有 feature/层中新增一个 file。
- **需要 domain/use-case 层吗?**仅当逻辑跨越多个 repository 时才需要。单个 repository 的 CRUD 不需要。
- **需要 interface 吗?**仅当真实实现无法在 中运行时,或确实需要在开发版与生产版实现之间切换时才需要。明确说明它使哪个 fake 成为可能。
flutter test - 需要单独的 package 吗?仅当编译期边界具有承重作用——即一旦发生分歧就会造成正确性 bug(规范单位/金额运算、完整 data 层、scheduler)。参见 中的拒绝过度设计对照表。
references/right-sizing.md
**使用多 package(workspace)时。**大型应用(多个团队、可进行 golden test 的纯 Dart core、可复用 design system)可以在 Dart pub workspace 下将基础层拆分为 package。此时:每个成员都设置并共用一个根目录的resolution: workspace;每个 package 仅公开一个 barrel(pubspec.lock),其下使用私有core.dart——绝不导入其他 package 的src/;纯 Dart 的src/package 不声明任何coredependency,因此误导入会直接产生编译错误;DAG 保持无环(flutter→ 无内部依赖;其他所有层 →core;app shell → 全部)。这是大型应用逐步演进后可采用的方案,绝不是小型应用的必备要求——默认仍是使用文件夹组织的单一 package。core
Anti-patterns
反模式
- A / domain layer wrapping one repository call. Pure ceremony; a rename of the repository method. Add the layer only when logic spans repositories.
*UseCase - An whose only content is the word "Repository", over code that runs in a test. The seam buys nothing; a Map-backed fake can even accept rows the real schema rejects. Test the concrete class against a real in-memory store.
abstract interface class - Business logic, formatting, or number/unit math in a View. Move it to the ViewModel or .
core - /
http/sqflite/a plugin called insideSharedPreferencesorbuild(). Data access belongs behind a repository, reached through a provider.initState() - Persist-after-publish / optimistic write before the commit returns. A crash in the gap credits state that never saved. Persist first, then the stream republishes.
- A stored counter mirroring derivable data (a column next to the rows). It drifts. Derive it from the source of truth.
count - A ViewModel importing for
package:flutter/material.dart/widgets. ViewModels are UI-framework-light; passingBuildContextinto the data layer is worse.BuildContext - /
get_it/injectableas a second DI container alongside Riverpod, or a global singleton /package:providermutable store reached from a widget. Providers are the one DI mechanism.static - A cross-feature import creating a cycle. Share via a foundation layer or navigate by route ID.
- Splitting a small app into packages "to be clean". Multiplies pubspecs and codegen for zero compile-time guarantee. Promote to a package only for a load-bearing wall.
- **仅用 / domain 层包装一次 repository 调用。**纯粹的形式主义,只是给 repository 方法换了名字。只有当逻辑跨越多个 repository 时才添加该层。
*UseCase - **在本来就能在测试中运行的代码上定义仅包含“Repository”字样的 。**该接缝没有带来任何价值;基于 Map 的 fake 甚至可能接受真实 schema 会拒绝的数据。应使用真实 in-memory store 测试具体类。
abstract interface class - **在 View 中放置业务逻辑、格式化或数值/单位运算。**将其移至 ViewModel 或 。
core - **在 或
build()内调用initState()/http/sqflite/plugin。**数据访问必须置于 repository 之后,并通过 provider 访问。SharedPreferences - **先发布后持久化,或在 commit 返回前执行 optimistic write。**两者之间发生崩溃会让实际未保存的状态生效。应先持久化,再由 stream 重新发布。
- 保存一个可派生数据的计数器(在行数据旁额外保存 列)。它会失去同步,应从事实来源派生。
count - **ViewModel 为获取 /widget 而导入
BuildContext。**ViewModel 应尽量不依赖 UI framework;将package:flutter/material.dart传入 data 层则更加不可取。BuildContext - **在 Riverpod 旁使用 /
get_it/injectable作为第二个 DI 容器,或允许 widget 访问 global singleton /package:providermutable store。**Provider 是唯一的 DI 机制。static - **通过跨 feature import 形成 cycle。**应通过基础层共享,或按 route ID 导航。
- **将小型应用拆分为多个 package,“只是因为这样更整洁”。**这会增加 pubspec 和 codegen,却无法提供任何编译期保证。只有当编译期边界具有承重作用时,才将其提升为 package。
Definition of done
完成标准
- New code lives under the right or
features/<x>//corelocation; grouping is feature-first.data - The View is a dumb — no data access, no business logic, no formatting, no
ConsumerWidget.try/catch - The ViewModel is a /
Notifier/AsyncNotifierexposing immutable state + intent methods; no public setters, noStreamNotifierin the Riverpod path.notifyListeners() - Every mutation routes through one repository method that persists before publishing; the watched stream re-emits (no manual republish); derived reads are streams/derived providers, not stored counters.
- Repositories map storage rows/DTOs → immutable value objects; no Drift/DTO/type reaches a ViewModel or widget.
Map - Interfaces exist only where the real impl can't run in a test (or a real dev/prod swap); each earns a named fake.
- Dependencies are injected via providers from a composition root; no new globals/singletons; no outside an injected clock.
DateTime.now() - A domain/use-case layer was added only if logic spans repositories; the app is a single package unless a compile wall is load-bearing.
- passes;
scripts/check_architecture.shis clean.dart analyze
- 新代码位于正确的 或
features/<x>//core位置;组织方式以 feature 优先。data - View 是 dumb ——不访问数据,不包含业务逻辑、格式化或
ConsumerWidget。try/catch - ViewModel 是 /
Notifier/AsyncNotifier,公开不可变状态和意图方法;没有公共 setter,Riverpod 路径中也没有StreamNotifier。notifyListeners() - 每次 mutation 都通过一个 repository 方法完成,并在发布前持久化;被监听的 stream 会重新发出数据(不手动重新发布);派生读取使用 stream/derived provider,而不是存储计数器。
- Repository 将存储行/DTO 映射为不可变值对象;Drift/DTO/类型不会到达 ViewModel 或 widget。
Map - Interface 仅存在于真实实现无法在测试中运行(或确实需要开发版/生产版切换)的情况下;每个 interface 都有明确对应的 fake。
- 依赖通过 composition root 中的 provider 注入;不新增 global/singleton;注入 clock 之外不调用 。
DateTime.now() - 仅当逻辑跨越多个 repository 时才添加 domain/use-case 层;除非编译期边界具有承重作用,否则应用保持为单一 package。
- 通过;
scripts/check_architecture.sh无问题。dart analyze
Related skills
相关 skill
- See for the Notifier/AsyncNotifier API, watch/read/listen split,
state-management-riverpod+family, and stale-closure hazards.autoDispose - See for the deep dive on building the dumb View (rule 5): const widget classes over
widget-compositionhelpers, lean_buildX(), and where the widget sits in this layer DAG.build() - See for the step-by-step feature folder + typed go_router registration workflow.
scaffold-feature-module - See for pubspec-as-audit-artifact, barrels, and one-way layering mechanics.
project-structure-and-packages - See for main() ordering, global error handlers, and DI overrides at the root.
app-startup-and-bootstrap - See for the sealed
error-handling-typed-results/Resultspine returned across boundaries.Failure - See for sealed types, exhaustive switches, and immutable value types.
dart3-idioms-and-coding-standards - See for the
naming-conventions/Screen/Notifier/Repository/Servicerole suffixes a grep can read.Failure - See for the DAO/repository seam and transaction-per-mutation persistence.
persistence-drift
- 有关 Notifier/AsyncNotifier API、watch/read/listen 区分、+
family和 stale-closure 隐患,参见autoDispose。state-management-riverpod - 有关构建 dumb View 的深入说明(规则 5),参见 :优先使用 const widget class 而非
widget-compositionhelper、保持_buildX()精简,并明确 widget 在 layer DAG 中的位置。build() - 有关 feature 文件夹和 typed go_router 注册的完整流程,参见 。
scaffold-feature-module - 有关 pubspec 作为审计工具、barrel 和单向分层机制,参见 。
project-structure-and-packages - 有关 顺序、全局 error handler 和根部 DI override,参见
main()。app-startup-and-bootstrap - 有关跨边界返回的 sealed /
Result主干结构,参见Failure。error-handling-typed-results - 有关 sealed type、穷尽式 switch 和不可变值类型,参见 。
dart3-idioms-and-coding-standards - 有关可通过 grep 识别的 /
Screen/Notifier/Repository/Service角色后缀,参见Failure。naming-conventions - 有关 DAO/repository 接缝和每次 mutation 使用 transaction 持久化,参见 。
persistence-drift
References
参考资料
Provider / ChangeNotifier appendix
Provider / ChangeNotifier 附录
The same rules map onto the official Flutter-guide stack ( + ) when
a codebase uses it instead of Riverpod. Rules 1–9, 11, 12 are unchanged. Only the "how" of state + DI
differs:
package:providerChangeNotifier- ViewModel = . It still holds private mutable fields and exposes intent methods; after a real state change it calls
ChangeNotifieronce — never insidenotifyListeners()and never in a tight loop. Expose state via getters that return unmodifiable views (build()). Immutability still applies to the domain models the ViewModel holds (List.unmodifiable, value equality).copyWith - DI = constructor injection wired through near the root. A
providerat the app root creates services and repositories; a screen'sMultiProviderbuilds its ViewModel fromChangeNotifierProvider. Depend on the abstract repository type so tests inject a fake.context.read<XRepository>() - Read vs listen: /
context.watch<T>()to rebuild on change;Consumerin callbacks. Never passcontext.read<T>()down into the data layer to read providers — pass the data.BuildContext - The bans still hold: no /service locator reached from a widget, no global mutable state, no data access in a View. Everything else in this skill (layering, single write path, derive-don't-store, map-at-the-boundary, abstract-only-what-you-can't-test, folder-vs-package) is identical.
get_it
当代码库使用 Flutter 官方指南中的技术栈( + )而非 Riverpod 时,相同规则仍可映射到该技术栈。规则 1–9、11、12 保持不变;只有状态管理与 DI 的“实现方式”有所不同:
package:providerChangeNotifier- ViewModel = 。它仍然持有私有可变字段并公开意图方法;发生真实状态变化后,仅调用一次
ChangeNotifier——绝不在notifyListeners()内调用,也绝不在紧凑循环中调用。通过 getter 公开状态,并返回不可修改视图(build())。不可变性同样适用于 ViewModel 持有的领域模型(List.unmodifiable、值相等性)。copyWith - **DI = 构造函数注入,通过根部的 接线。**应用根部的
provider创建 service 和 repository;screen 的MultiProvider使用ChangeNotifierProvider构建 ViewModel。依赖 abstract repository 类型,使测试能够注入 fake。context.read<XRepository>() - **读取与监听:**使用 /
context.watch<T>()触发重建;在 callback 中使用Consumer。绝不能将context.read<T>()向下传入 data 层以读取 provider——应直接传递数据。BuildContext - 各项禁令仍然有效:不允许 widget 访问 /service locator,不允许 global mutable state,不允许在 View 中访问数据。除此之外,本 skill 中的所有规则(分层、单一写入路径、派生而非存储、在边界映射、只抽象无法测试的部分、folder 与 package 的取舍)完全相同。
get_it