flutter-architecture

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Flutter 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
*UseCase
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.
Read the reference for the task at hand:
  • references/module-and-layers.md
    — the layer model, folder-vs-package continuum, the DAG, barrels, feature-folder anatomy, and the "when multi-package (workspace)" note.
  • references/right-sizing.md
    — the reject-over-engineering table, "abstract only what you can't test", and how architecture scales with app size.
  • references/state-di-riverpod.md
    — provider graph, keepAlive vs autoDispose, placeholder-override composition root, isolate-safe factories,
    ProviderContainer
    tests.
Run
scripts/check_architecture.sh
before opening a PR.
将每个 Flutter 应用组织为与规模相适配的分层、功能优先 MVVM 系统。你必须始终能在一秒内回答“这段代码应该放在哪里?”。本指南基于 Flutter 官方《应用架构指南》,并使用 Riverpod 3.x 作为状态管理与依赖注入的唯一机制。
两种失败模式会毁掉架构:结构不足(widget 直接访问数据库)和结构过度(用一个
*UseCase
包装一次 repository 调用,或为已经能在测试中运行的代码添加 interface)。本 skill 同时防范这两种问题。从小处开始;只有当新增一层承载了你能明确说明的职责时,才添加这一层。
针对当前任务阅读参考资料:
  • references/module-and-layers.md
    ——层级模型、文件夹与 package 的连续谱、DAG、barrel、feature 文件夹结构,以及“何时使用多 package(workspace)”的说明。
  • references/right-sizing.md
    ——拒绝过度设计的对照表、“只抽象无法测试的部分”,以及架构如何随应用规模扩展。
  • references/state-di-riverpod.md
    ——provider graph、keepAlive 与 autoDispose、placeholder override composition root、isolate-safe factory、
    ProviderContainer
    测试。
开启 PR 前运行
scripts/check_architecture.sh
。

Non-negotiable rules

不可妥协的规则

  1. Answer "where does this belong?" in one second. Group by feature first, layer second. No giant app-wide
    screens/
    ,
    models/
    , or
    widgets/
    bucket — those smear one feature across the tree and force a name lookup on every edit.
  2. Two layers minimum: UI and Data. A domain/use-case layer only when logic spans multiple repositories (projection, aggregation, a multi-step workflow). A
    *UseCase
    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.
  3. 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
    flutter test
    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.
  4. Data flows one way; never skip or reverse a hop. Data down:
    Service → Repository → ViewModel → View
    . Events up:
    View → ViewModel → Repository
    . A widget calls its ViewModel only; a ViewModel calls repositories only. No two-way binding, no widget reaching a data source.
  5. The View is dumb. A View does layout,
    if
    /
    switch
    on state, animation, and navigation — nothing else. No business logic, no formatting/number math, no
    try/catch
    , no data access. If a widget computes or fetches, it's in the wrong layer.
  6. One ViewModel per feature, over immutable state. The ViewModel holds private mutable state and exposes intent methods (
    load()
    ,
    add(...)
    ); every transition assigns a new immutable value with value equality. No public setters, no mutable field the UI edits in place.
  7. 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.
  8. 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.
  9. 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
    Map
    never reaches a ViewModel or widget; unit math and locale formatting never happen in a widget.
  10. Inject through providers; depend on the abstraction where it earns one. No globals, no singletons, no service locator reached from a widget, no
    DateTime.now()
    outside an injected
    Clock
    . A composition root wires the object graph once.
  11. 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.
  12. Errors are typed values at boundaries. Repositories/use-cases return a sealed
    Result
    /
    Failure
    rather than throwing across a layer; the UI switches exhaustively. See
    error-handling-typed-results
    .
  1. **在一秒内回答“它应该放在哪里?”**首先按 feature 划分,再按 layer 划分。不要建立应用级的巨大
    screens/
    、
    models/
    或
    widgets/
    目录;这种结构会把同一个 feature 分散到目录树中,导致每次修改都要查找名称。
  2. 至少两层:UI 和 Data。仅当逻辑跨越多个 repository 时,才添加 domain/use-case 层(投影、聚合、多步骤工作流)。仅转发一次 repository 调用的
    *UseCase
    只是改名,并非真正的边界——Flutter 官方指南将 domain 层视为条件性设计,并指出大多数应用都不需要它。
  3. 只抽象那些确实无法在测试中运行的部分——并明确说明该抽象使什么变得可测试。无法在
    flutter test
    中执行的 platform channel、network client 或 plugin 才值得拥有 interface + fake。已经在 headless 环境运行的代码(in-memory DB、pure calculator、基于其实现的 repository)应保持
    具体
    。“更整洁”不是有效职责;如果无法说明它带来的测试接缝,就不要添加。
  4. **数据只能单向流动;绝不能跳过或反向跨越任何一层。**数据向下:
    Service → Repository → ViewModel → View
    。事件向上:
    View → ViewModel → Repository
    。widget 只能调用自己的 ViewModel;ViewModel 只能调用 repository。禁止双向绑定,禁止 widget 直接访问数据源。
  5. **View 是 dumb 的。**View 只负责布局、基于状态执行
    if
    /
    switch
    、动画和导航——不做其他事情。不允许业务逻辑、格式化/数值计算、
    try/catch
    或数据访问。如果 widget 执行计算或获取数据,就说明它位于错误的层。
  6. 每个 feature 使用一个基于不可变状态的 ViewModel。ViewModel 持有私有可变状态,并公开意图方法(
    load()
    、
    add(...)
    );每次状态转换都赋值一个具有值相等性的新不可变值。不允许公共 setter,也不允许 UI 原地修改可变字段。
  7. Repository 既是单一事实来源,也是单一写入路径。每次 mutation 都通过一个有明确名称的 repository 方法完成,并且先持久化,再发布(存储支持时使用一个 transaction)。绝不能先发布后持久化——两者之间发生崩溃会让实际未保存的状态生效。
  8. 派生,不要存储。计数、总计、连续天数、筛选列表应从事实来源计算(通过 stream/derived provider),绝不能保存可能失去同步的第二个计数器。
  9. 在边界处映射;领域类型不得进入外部层。Repository 将存储行/JSON DTO 映射为不可变的领域值对象。生成的 Drift row 或
    Map
    绝不能到达 ViewModel 或 widget;单位换算和 locale 格式化绝不能发生在 widget 中。
  10. **通过 provider 注入;在真正值得抽象的地方依赖抽象。**禁止 globals、singletons,禁止 widget 访问 service locator,禁止在注入的
    Clock
    之外使用
    DateTime.now()
    。composition root 只组装一次对象图。
  11. Feature 是 FOLDER;只有当编译期边界具有承重作用时,基础层才成为 PACKAGE。默认采用单一 package。一个 feature 绝不导入另一个 feature——应通过基础层共享,或按 route ID 导航。依赖图必须是严格只向下的 DAG。
  12. **错误在边界处以类型化值表示。**Repository/use-case 返回 sealed
    Result
    /
    Failure
    ,而不是跨层抛出异常;UI 对其进行穷尽式 switch。参见
    error-handling-typed-results
    。

The layered shape (single package, the default)

分层结构(单一 package,默认)

project-structure-and-packages
OWNS the physical tree; this is the feature-first layout it defines, shown here for the layer semantics. Features are FOLDERS under
lib/features/
; a feature's Views and its one ViewModel live in
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:
core/
depends on nothing above it and stays free of
BuildContext
;
data/
has no Flutter UI imports; a feature depends on
core
/
data
/
services
, never on a sibling feature. Add a feature-local
domain/
+
application/
(use-cases) folder only when logic spans repositories.
project-structure-and-packages
负责物理目录结构;下面展示它定义的功能优先布局,以说明各层语义。Feature 是
lib/features/
下的 FOLDER;某个 feature 的 View 及其唯一的 ViewModel 位于
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/
经验法则:
core/
不依赖其上任何层,并保持不包含
BuildContext
;
data/
不导入 Flutter UI;一个 feature 可以依赖
core
/
data
/
services
,但绝不依赖同级 feature。仅当逻辑跨越多个 repository 时,才添加 feature 内的
domain/
+
application/
(use-case)目录。

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
watchTasks()
stream plus an
add()
that persists first, then the stream re-emits. Give it an
abstract interface
only when the real impl can't run in a test (rule 3); over an in-memory DB a concrete class is fine.
dart
// 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
ref.watch
, key per-entity state with
family
, and use
autoDispose
for per-screen controllers. See
state-management-riverpod
for the full API discipline (watch/read/listen split,
.select
, stale-closure hazards).
一个纯展示 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 既是单一事实来源,也是单一写入路径——包含一个
watchTasks()
stream,以及负责先持久化、随后由 stream 重新发出数据的
add()
。只有在真实实现无法在测试中运行时,才为它定义
abstract interface
(规则 3);对于 in-memory DB,使用具体类即可。
dart
// 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 就是依赖注入。通过
ref.watch
绑定依赖,以
family
按实体划分状态,并对屏幕级 controller 使用
autoDispose
。完整的 API 规范参见
state-management-riverpod
(watch/read/listen 区分、
.select
、stale-closure 隐患)。

The 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
bootstrap.dart
— the same seam tests use.
dart
// 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)
keepAlive
; never
autoDispose
a singleton that can be torn down mid-operation. See
app-startup-and-bootstrap
for main() ordering and error handlers.
异步构建的基础设施(数据库、目录、key store)通过 placeholder provider 注入;这些 provider 在被覆盖前直接抛出异常,并统一在
bootstrap.dart
中覆盖——测试也复用同一接缝。
dart
// 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)为
keepAlive
;绝不能
autoDispose
一个可能在操作执行中途被销毁的 singleton。
main()
的顺序和错误 handler 参见
app-startup-and-bootstrap
。

Right-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
    flutter test
    , or you genuinely swap dev/prod impls. Name the fake it enables.
  • 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 sets
resolution: workspace
with one root
pubspec.lock
; each package exposes one barrel (
core.dart
) over a private
src/
— never import another package's
src/
; the pure-Dart
core
package declares no
flutter
dependency so a stray import is a compile error; the DAG stays acyclic (
core
→ 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.
根据应用规模调整架构。依次回答三个问题:
  • **需要新增 folder 还是 file?**通常只需在现有 feature/层中新增一个 file。
  • **需要 domain/use-case 层吗?**仅当逻辑跨越多个 repository 时才需要。单个 repository 的 CRUD 不需要。
  • **需要 interface 吗?**仅当真实实现无法在
    flutter test
    中运行时,或确实需要在开发版与生产版实现之间切换时才需要。明确说明它使哪个 fake 成为可能。
  • 需要单独的 package 吗?仅当编译期边界具有承重作用——即一旦发生分歧就会造成正确性 bug(规范单位/金额运算、完整 data 层、scheduler)。参见
    references/right-sizing.md
    中的拒绝过度设计对照表。
**使用多 package(workspace)时。**大型应用(多个团队、可进行 golden test 的纯 Dart core、可复用 design system)可以在 Dart pub workspace 下将基础层拆分为 package。此时:每个成员都设置
resolution: workspace
并共用一个根目录的
pubspec.lock
;每个 package 仅公开一个 barrel(
core.dart
),其下使用私有
src/
——绝不导入其他 package 的
src/
;纯 Dart 的
core
package 不声明任何
flutter
dependency,因此误导入会直接产生编译错误;DAG 保持无环(
core
→ 无内部依赖;其他所有层 →
core
;app shell → 全部)。这是大型应用逐步演进后可采用的方案,绝不是小型应用的必备要求——默认仍是使用文件夹组织的单一 package。

Anti-patterns

反模式

  • A
    *UseCase
    / domain layer wrapping one repository call.
    Pure ceremony; a rename of the repository method. Add the layer only when logic spans repositories.
  • An
    abstract interface class
    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.
  • Business logic, formatting, or number/unit math in a View. Move it to the ViewModel or
    core
    .
  • http
    /
    sqflite
    /
    SharedPreferences
    /a plugin called inside
    build()
    or
    initState()
    .
    Data access belongs behind a repository, reached through a provider.
  • 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
    count
    column next to the rows). It drifts. Derive it from the source of truth.
  • A ViewModel importing
    package:flutter/material.dart
    for
    BuildContext
    /widgets.
    ViewModels are UI-framework-light; passing
    BuildContext
    into the data layer is worse.
  • get_it
    /
    injectable
    /
    package:provider
    as a second DI container alongside Riverpod, or a global singleton /
    static
    mutable store reached from a widget.
    Providers are the one DI mechanism.
  • 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.
  • **仅用
    *UseCase
    / domain 层包装一次 repository 调用。**纯粹的形式主义,只是给 repository 方法换了名字。只有当逻辑跨越多个 repository 时才添加该层。
  • **在本来就能在测试中运行的代码上定义仅包含“Repository”字样的
    abstract interface class
    。**该接缝没有带来任何价值;基于 Map 的 fake 甚至可能接受真实 schema 会拒绝的数据。应使用真实 in-memory store 测试具体类。
  • **在 View 中放置业务逻辑、格式化或数值/单位运算。**将其移至 ViewModel 或
    core
    。
  • **在
    build()
    或
    initState()
    内调用
    http
    /
    sqflite
    /
    SharedPreferences
    /plugin。**数据访问必须置于 repository 之后,并通过 provider 访问。
  • **先发布后持久化,或在 commit 返回前执行 optimistic write。**两者之间发生崩溃会让实际未保存的状态生效。应先持久化,再由 stream 重新发布。
  • 保存一个可派生数据的计数器(在行数据旁额外保存
    count
    列)。它会失去同步,应从事实来源派生。
  • **ViewModel 为获取
    BuildContext
    /widget 而导入
    package:flutter/material.dart
    。**ViewModel 应尽量不依赖 UI framework;将
    BuildContext
    传入 data 层则更加不可取。
  • **在 Riverpod 旁使用
    get_it
    /
    injectable
    /
    package:provider
    作为第二个 DI 容器,或允许 widget 访问 global singleton /
    static
    mutable store。**Provider 是唯一的 DI 机制。
  • **通过跨 feature import 形成 cycle。**应通过基础层共享,或按 route ID 导航。
  • **将小型应用拆分为多个 package,“只是因为这样更整洁”。**这会增加 pubspec 和 codegen,却无法提供任何编译期保证。只有当编译期边界具有承重作用时,才将其提升为 package。

Definition of done

完成标准

  • New code lives under the right
    features/<x>/
    or
    core
    /
    data
    location; grouping is feature-first.
  • The View is a dumb
    ConsumerWidget
    — no data access, no business logic, no formatting, no
    try/catch
    .
  • The ViewModel is a
    Notifier
    /
    AsyncNotifier
    /
    StreamNotifier
    exposing immutable state + intent methods; no public setters, no
    notifyListeners()
    in the Riverpod path.
  • 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/
    Map
    type reaches a ViewModel or widget.
  • 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
    DateTime.now()
    outside an injected clock.
  • 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.
  • scripts/check_architecture.sh
    passes;
    dart analyze
    is clean.
  • 新代码位于正确的
    features/<x>/
    或
    core
    /
    data
    位置;组织方式以 feature 优先。
  • View 是 dumb
    ConsumerWidget
    ——不访问数据,不包含业务逻辑、格式化或
    try/catch
    。
  • ViewModel 是
    Notifier
    /
    AsyncNotifier
    /
    StreamNotifier
    ,公开不可变状态和意图方法;没有公共 setter,Riverpod 路径中也没有
    notifyListeners()
    。
  • 每次 mutation 都通过一个 repository 方法完成,并在发布前持久化;被监听的 stream 会重新发出数据(不手动重新发布);派生读取使用 stream/derived provider,而不是存储计数器。
  • Repository 将存储行/DTO 映射为不可变值对象;Drift/DTO/
    Map
    类型不会到达 ViewModel 或 widget。
  • 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
    state-management-riverpod
    for the Notifier/AsyncNotifier API, watch/read/listen split,
    family
    +
    autoDispose
    , and stale-closure hazards.
  • See
    widget-composition
    for the deep dive on building the dumb View (rule 5): const widget classes over
    _buildX()
    helpers, lean
    build()
    , and where the widget sits in this layer DAG.
  • See
    scaffold-feature-module
    for the step-by-step feature folder + typed go_router registration workflow.
  • See
    project-structure-and-packages
    for pubspec-as-audit-artifact, barrels, and one-way layering mechanics.
  • See
    app-startup-and-bootstrap
    for main() ordering, global error handlers, and DI overrides at the root.
  • See
    error-handling-typed-results
    for the sealed
    Result
    /
    Failure
    spine returned across boundaries.
  • See
    dart3-idioms-and-coding-standards
    for sealed types, exhaustive switches, and immutable value types.
  • See
    naming-conventions
    for the
    Screen
    /
    Notifier
    /
    Repository
    /
    Service
    /
    Failure
    role suffixes a grep can read.
  • See
    persistence-drift
    for the DAO/repository seam and transaction-per-mutation persistence.
  • 有关 Notifier/AsyncNotifier API、watch/read/listen 区分、
    family
    +
    autoDispose
    和 stale-closure 隐患,参见
    state-management-riverpod
    。
  • 有关构建 dumb View 的深入说明(规则 5),参见
    widget-composition
    :优先使用 const widget class 而非
    _buildX()
    helper、保持
    build()
    精简,并明确 widget 在 layer DAG 中的位置。
  • 有关 feature 文件夹和 typed go_router 注册的完整流程,参见
    scaffold-feature-module
    。
  • 有关 pubspec 作为审计工具、barrel 和单向分层机制,参见
    project-structure-and-packages
    。
  • 有关
    main()
    顺序、全局 error handler 和根部 DI override,参见
    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 (
package:provider
+
ChangeNotifier
) when a codebase uses it instead of Riverpod. Rules 1–9, 11, 12 are unchanged. Only the "how" of state + DI differs:
  • ViewModel =
    ChangeNotifier
    .
    It still holds private mutable fields and exposes intent methods; after a real state change it calls
    notifyListeners()
    once — never inside
    build()
    and never in a tight loop. Expose state via getters that return unmodifiable views (
    List.unmodifiable
    ). Immutability still applies to the domain models the ViewModel holds (
    copyWith
    , value equality).
  • DI = constructor injection wired through
    provider
    near the root.
    A
    MultiProvider
    at the app root creates services and repositories; a screen's
    ChangeNotifierProvider
    builds its ViewModel from
    context.read<XRepository>()
    . Depend on the abstract repository type so tests inject a fake.
  • Read vs listen:
    context.watch<T>()
    /
    Consumer
    to rebuild on change;
    context.read<T>()
    in callbacks. Never pass
    BuildContext
    down into the data layer to read providers — pass the data.
  • The bans still hold: no
    get_it
    /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.
当代码库使用 Flutter 官方指南中的技术栈(
package:provider
+
ChangeNotifier
)而非 Riverpod 时,相同规则仍可映射到该技术栈。规则 1–9、11、12 保持不变;只有状态管理与 DI 的“实现方式”有所不同:
  • ViewModel =
    ChangeNotifier
    。它仍然持有私有可变字段
    并公开意图方法;发生真实状态变化后,仅调用一次
    notifyListeners()
    ——绝不在
    build()
    内调用,也绝不在紧凑循环中调用。通过 getter 公开状态,并返回不可修改视图(
    List.unmodifiable
    )。不可变性同样适用于 ViewModel 持有的领域模型(
    copyWith
    、值相等性)。
  • **DI = 构造函数注入,通过根部的
    provider
    接线。**应用根部的
    MultiProvider
    创建 service 和 repository;screen 的
    ChangeNotifierProvider
    使用
    context.read<XRepository>()
    构建 ViewModel。依赖 abstract repository 类型,使测试能够注入 fake。
  • **读取与监听:**使用
    context.watch<T>()
    /
    Consumer
    触发重建;在 callback 中使用
    context.read<T>()
    。绝不能将
    BuildContext
    向下传入 data 层以读取 provider——应直接传递数据。
  • 各项禁令仍然有效:不允许 widget 访问
    get_it
    /service locator,不允许 global mutable state,不允许在 View 中访问数据。除此之外,本 skill 中的所有规则(分层、单一写入路径、派生而非存储、在边界映射、只抽象无法测试的部分、folder 与 package 的取舍)完全相同。