Flutter MVVM Architecture
This skill encodes the Flutter team's official recommended app architecture:
https://docs.flutter.dev/app-architecture, including the
core architecture concepts
(separation of concerns, single source of truth, unidirectional data flow,
immutable state) summarized under "Core principles" below. It's the same
architecture used in Flutter's reference sample, the
Compass app.
Apply it by default whenever generating or reviewing non-trivial Flutter code
(more than a single throwaway widget). These are the Flutter team's
recommendations, not rigid law — treat them as strong defaults, and adapt
when a repo already has an established, different convention (e.g. it's
already fully built on riverpod or flutter_bloc). Even then, keep the
underlying principles: separation of concerns, single source of truth,
unidirectional data flow, and dumb widgets.
Verified against the live docs on 2026-08-14 (site showed Flutter 3.44.7,
pages last updated May–July 2026). If provider, go_router, or freezed
ship a breaking major version, or docs.flutter.dev/app-architecture shows a
materially newer revision, re-check that page before trusting the
package-specific code samples in this skill.
Why this matters
Good architecture makes Flutter apps easier to maintain, test, and scale
across a growing team, and it's what most production Flutter codebases
converge on. Code that mixes network calls, business logic, and widget code
in one StatefulWidget works for a demo but rapidly becomes unmaintainable
and untestable. Defaulting to this layered structure avoids that outcome
without meaningfully slowing down simple requests.
Core principles (always apply, regardless of feature size)
- Separation of concerns. Split the app into a UI layer and a
data layer (plus an optional domain layer). Layers may only talk to
the layer directly above or below them — the UI layer never touches the
data layer directly, and vice versa.
- Single source of truth (SSOT). Every type of data has exactly one
owner: a Repository. If data can change, the repository is the only
class allowed to change it.
- Unidirectional data flow (UDF). User events flow UI → logic → data.
New state flows data → logic → UI. Data never mutates in place inside a
widget or view model.
- UI is a function of (immutable) state. Widgets render, they don't
decide. Data should be immutable; when it changes, a new instance is
created and the UI rebuilds in response.
- Widgets stay dumb. A widget/View should hold as little logic as
possible — see the exact allowed list under Views below.
The four core components
MVVM here maps View + ViewModel to the UI layer, and Repository +
Service to the Model layer of classic MVVM.
| Component |
Layer |
Responsibility |
Depends on |
| View |
UI |
A widget or composition of widgets for one feature (often, not always, a full screen with a Scaffold). Renders data, forwards user events. No business logic. |
Exactly one ViewModel |
| ViewModel |
UI |
Converts domain data into UI state; exposes Commands (callbacks) that Views attach to event handlers; calls notifyListeners() when state changes. |
One or more Repositories (and/or Use-cases) |
| Use-case (optional, domain layer) |
Domain |
Encapsulates business logic that's reused across ViewModels or that merges data from multiple repositories. Only add when needed — see references/recommendations.md. |
One or more Repositories |
| Repository |
Data |
The single source of truth for one type of application data. Polls/refreshes services, caches, retries, and transforms raw data into domain models. |
One or more Services |
| Service |
Data |
A stateless wrapper around exactly one external data source (REST API, platform plugin, local database, local files). Holds no state, has no business logic. |
Nothing else in the app |
A View and ViewModel have a strict one-to-one relationship and together
define one "feature" (not always a full screen — e.g. a reusable
LogoutButton/LogoutViewModel pair). Repositories and ViewModels have a
many-to-many relationship, as do Services and Repositories.
When to add a domain layer
Add a Use-case only when at least one of these is true — otherwise let
ViewModels call Repositories directly, which is the default:
- The logic merges data from multiple repositories.
- The same logic is reused by more than one ViewModel.
- The logic is exceedingly complex and crowds the ViewModel.
Default to skipping it. A single-repository CRUD screen with no shared logic
doesn't need a use-case just to feel "more layered" — that's added
boilerplate and mocking overhead with no testability or reuse benefit.
For full code walkthroughs of each component, read:
references/ui-layer.md — Views, ViewModels, UI state, the Command pattern
references/data-layer.md — Repositories, Services, domain models, Result
Rules of engagement (who may talk to whom)
| Component |
Allowed to know about |
Never allowed to know about |
| View |
Exactly one ViewModel (passed into its constructor) |
Any repository, service, or other view model |
| ViewModel |
One or more Repositories / Use-cases (passed into its constructor, stored as private fields) |
That a View exists, other ViewModels |
| Repository |
One or more Services (passed into its constructor, stored as private fields) |
Other repositories, any ViewModel |
| Service |
Nothing else in the app |
Repositories, ViewModels, Views |
Always inject dependencies through constructors (required this.xRepository)
and store them as private (_-prefixed) fields — this is what stops a View
from reaching past its ViewModel into the data layer. See
references/dependency-injection.md for the full wiring pattern
(the Flutter team recommends package:provider; get_it/injectable
service-locator-style DI is a valid alternative if a repo already uses it —
the constructor-injection and privacy rules above still apply either way).
Workflow for building or reviewing a feature
- Identify the feature — it's exactly one View + one ViewModel pair.
Name them
<Feature>Screen/<Feature>View and <Feature>ViewModel.
- Identify the data types the feature needs. Each distinct type of
data gets (or reuses) its own
Repository (e.g. UserRepository,
BookingRepository). Don't let one repository own multiple unrelated
data types, and don't let repositories know about each other — if two
repositories' data needs to be combined, do that in the ViewModel or a
use-case, not the repository.
- Identify the external sources the data comes from. Each REST API,
platform plugin, or local database gets its own
Service
(e.g. ApiClient, SharedPreferencesService). A repository composes
one or more services.
- Write the ViewModel. Constructor takes repositories/use-cases as
required named parameters; expose UI state via public getters backed by
private fields; expose actions as
Command objects (see
references/design-patterns.md); extend ChangeNotifier and call
notifyListeners() whenever state changes.
- Write the View. A widget whose only inputs are
key and the
ViewModel; wrap the parts that need to rebuild in ListenableBuilder
(listening to the ViewModel or, for finer control, to an individual
Command); forward taps/gestures straight to viewModel.someCommand.execute(...).
- Wire dependency injection at the app/router level — don't
instantiate repositories or services inside widgets or view models.
- Consider error handling and loading state up front using
Result
and Command (see references/design-patterns.md) rather than bolting
them on later — almost every real ViewModel action needs a
running/error/success representation.
- Write tests alongside the code: unit tests for the ViewModel against
a fake repository, unit tests for the repository against a fake service,
and widget tests for the View. See
references/testing.md.
Migrating existing code? If you're converting a StatefulWidget/
setState() screen rather than starting fresh, follow
references/migration.md instead of starting at step 1 above — it walks the
same end state through incremental, compilable steps.
Auditing existing code for separation-of-concerns problems? Scan it
against references/audit-checklist.md rather than rebuilding the workflow
above from scratch.
Recommended project structure
lib/
ui/
core/ # shared widgets & themes used by multiple features
ui/
themes/
<feature_name>/
view_models/
<feature>_view_model.dart
widgets/
<feature>_screen.dart
<other widgets specific to this feature>
domain/
models/
<model_name>.dart # domain models, shared by data + ui layers
data/
repositories/
<repository_name>.dart
services/
<service_name>.dart
model/
<api_model_name>.dart # raw API/DB models, distinct from domain models
config/
utils/
routing/
main_development.dart
main_staging.dart
main.dart
test/ # mirrors lib/ — unit + widget tests
testing/ # fakes and mocks shared across test files
fakes/
models/
Notes on this structure (from the Flutter team, based on the Compass app):
data/ is organized by type (repositories, services) because those
classes are reused across features.
ui/ is organized by feature because each feature owns exactly one
View + ViewModel pair.
domain/models holds the shared domain model classes, since both the
data and UI layers depend on them.
- Multiple
main_*.dart entry points support different environments
(development/staging/production), typically wiring up different
repository implementations (e.g. BookingRepositoryRemote vs
BookingRepositoryLocal).
Non-negotiable rules when generating Flutter code
Apply these unless the user has explicitly asked for a different pattern or
the surrounding codebase clearly already follows one:
- Never put business logic, network calls, or data mutation inside a
widget's
build() method or event handlers. Only these are allowed
directly in a View: simple if/else to show/hide widgets based on a flag
from the ViewModel, animation logic, layout logic based on device info
(screen size/orientation), and simple routing.
- Never let a widget hold a
Repository or Service reference.
Widgets only ever see a ViewModel.
- Always make domain/UI-state data models immutable. Prefer
freezed
(or built_value) for data classes so copyWith/equality/serialization
are generated instead of hand-rolled.
- Always expose ViewModel actions as methods that can be attached to
event handlers — prefer the
Command pattern (see
references/design-patterns.md) over ad-hoc bool isLoading /
String? error fields duplicated per action.
- Always make repositories, not services, the thing ViewModels depend
on. A ViewModel should never import an API client or a database
service directly.
- Always use dependency injection (constructor injection, wired via
provider or an equivalent mechanism like get_it at the widget-tree or
router level) instead of singletons, global variables, or ad-hoc statics
reached for from inside business logic.
- Prefer
Result<T>-returning methods over throwing exceptions across
service/repository/view-model boundaries so callers can't forget to
catch (see references/design-patterns.md).
- Write tests that exploit the architecture: fake the repository to
test a ViewModel, fake the service to test a repository. If a class is
hard to fake or mock, that's a signal the class has too many
responsibilities or unclear inputs/outputs.
Reference files — read these for implementation detail
| File |
Read when you need... |
references/ui-layer.md |
Full View/ViewModel code patterns, UI state, ListenableBuilder wiring, the Command pattern in context, and disposing ViewModels/Commands/subscriptions |
references/data-layer.md |
Full Repository/Service code patterns, domain vs. API models, the Result pattern in context |
references/dependency-injection.md |
Wiring everything together with provider + go_router, the full rules-of-engagement table |
references/migration.md |
Converting a StatefulWidget/setState() screen into View + ViewModel + Repository, step by step |
references/testing.md |
Unit-testing ViewModels/Repositories with fakes, widget-testing Views |
references/audit-checklist.md |
A quick-scan list of architecture smells for reviewing existing code against this skill's rules |
references/design-patterns.md |
Full Command/Result class implementations, Optimistic State, key-value persistence, SQL persistence, offline-first strategies |
references/recommendations.md |
The Flutter team's full prioritized do/don't tables, naming conventions, and recommended packages/resources |
Load only the reference files relevant to the current task — don't read all
of them for a small, single-widget request.
1---2name: flutter-mvvm-architecture3description: Apply the Flutter team's official app-architecture guidelines (docs.flutter.dev/app-architecture, the MVVM pattern used by the Compass sample app) whenever writing, reviewing, refactoring, or reasoning about Flutter/Dart code. Trigger this for anything touching Flutter widgets, screens, ViewModels, state management, repositories, services, dependency injection, Provider, ChangeNotifier, Command objects, Result/error-handling types, or Flutter project/folder structure — even if the user doesn't say "architecture" or "MVVM" explicitly. Also trigger when scaffolding a new Flutter feature or screen, deciding where business logic or a network call should live, converting ad-hoc setState()/StatefulWidget logic into a layered design, adding persistence (SharedPreferences/SQL) or offline support, or auditing existing Flutter code for separation-of-concerns problems.4license: MIT5metadata:6 version: "1.0.0"7 source: https://skillmd.com/skills/reza00farjam/flutter-mvvm-architecture8 upstream: "https://docs.flutter.dev/app-architecture"9---1011# Flutter MVVM Architecture1213This skill encodes the Flutter team's official recommended app architecture:14<https://docs.flutter.dev/app-architecture>, including the15[core architecture concepts](https://docs.flutter.dev/app-architecture/concepts)16(separation of concerns, single source of truth, unidirectional data flow,17immutable state) summarized under "Core principles" below. It's the same18architecture used in Flutter's reference sample, the19[Compass app](https://github.com/flutter/samples/tree/main/compass_app).20Apply it by default whenever generating or reviewing non-trivial Flutter code21(more than a single throwaway widget). These are the Flutter team's22recommendations, not rigid law — treat them as strong defaults, and adapt23when a repo already has an established, different convention (e.g. it's24already fully built on `riverpod` or `flutter_bloc`). Even then, keep the25underlying principles: separation of concerns, single source of truth,26unidirectional data flow, and dumb widgets.2728> Verified against the live docs on 2026-08-14 (site showed Flutter 3.44.7,29> pages last updated May–July 2026). If `provider`, `go_router`, or `freezed`30> ship a breaking major version, or docs.flutter.dev/app-architecture shows a31> materially newer revision, re-check that page before trusting the32> package-specific code samples in this skill.3334## Why this matters3536Good architecture makes Flutter apps easier to maintain, test, and scale37across a growing team, and it's what most production Flutter codebases38converge on. Code that mixes network calls, business logic, and widget code39in one `StatefulWidget` works for a demo but rapidly becomes unmaintainable40and untestable. Defaulting to this layered structure avoids that outcome41without meaningfully slowing down simple requests.4243## Core principles (always apply, regardless of feature size)4445- **Separation of concerns.** Split the app into a **UI layer** and a46 **data layer** (plus an optional domain layer). Layers may only talk to47 the layer directly above or below them — the UI layer never touches the48 data layer directly, and vice versa.49- **Single source of truth (SSOT).** Every type of data has exactly one50 owner: a **Repository**. If data can change, the repository is the only51 class allowed to change it.52- **Unidirectional data flow (UDF).** User events flow UI → logic → data.53 New state flows data → logic → UI. Data never mutates in place inside a54 widget or view model.55- **UI is a function of (immutable) state.** Widgets render, they don't56 decide. Data should be immutable; when it changes, a new instance is57 created and the UI rebuilds in response.58- **Widgets stay dumb.** A widget/View should hold as little logic as59 possible — see the exact allowed list under Views below.6061## The four core components6263MVVM here maps `View` + `ViewModel` to the UI layer, and `Repository` +64`Service` to the Model layer of classic MVVM.6566| Component | Layer | Responsibility | Depends on |67|---|---|---|---|68| **View** | UI | A widget or composition of widgets for one feature (often, not always, a full screen with a `Scaffold`). Renders data, forwards user events. No business logic. | Exactly one ViewModel |69| **ViewModel** | UI | Converts domain data into UI state; exposes **Commands** (callbacks) that Views attach to event handlers; calls `notifyListeners()` when state changes. | One or more Repositories (and/or Use-cases) |70| **Use-case** *(optional, domain layer)* | Domain | Encapsulates business logic that's reused across ViewModels or that merges data from multiple repositories. Only add when needed — see `references/recommendations.md`. | One or more Repositories |71| **Repository** | Data | The single source of truth for one type of application data. Polls/refreshes services, caches, retries, and transforms raw data into **domain models**. | One or more Services |72| **Service** | Data | A stateless wrapper around exactly one external data source (REST API, platform plugin, local database, local files). Holds no state, has no business logic. | Nothing else in the app |7374A View and ViewModel have a strict **one-to-one** relationship and together75define one "feature" (not always a full screen — e.g. a reusable76`LogoutButton`/`LogoutViewModel` pair). Repositories and ViewModels have a77**many-to-many** relationship, as do Services and Repositories.7879### When to add a domain layer8081Add a Use-case only when at least one of these is true — otherwise let82ViewModels call Repositories directly, which is the default:83- The logic merges data from **multiple repositories**.84- The same logic is **reused by more than one ViewModel**.85- The logic is **exceedingly complex** and crowds the ViewModel.8687Default to skipping it. A single-repository CRUD screen with no shared logic88doesn't need a use-case just to feel "more layered" — that's added89boilerplate and mocking overhead with no testability or reuse benefit.9091For full code walkthroughs of each component, read:92- `references/ui-layer.md` — Views, ViewModels, UI state, the Command pattern93- `references/data-layer.md` — Repositories, Services, domain models, Result9495## Rules of engagement (who may talk to whom)9697| Component | Allowed to know about | Never allowed to know about |98|---|---|---|99| View | Exactly one ViewModel (passed into its constructor) | Any repository, service, or other view model |100| ViewModel | One or more Repositories / Use-cases (passed into its constructor, stored as **private** fields) | That a View exists, other ViewModels |101| Repository | One or more Services (passed into its constructor, stored as **private** fields) | Other repositories, any ViewModel |102| Service | Nothing else in the app | Repositories, ViewModels, Views |103104Always inject dependencies through constructors (`required this.xRepository`)105and store them as private (`_`-prefixed) fields — this is what stops a View106from reaching past its ViewModel into the data layer. See107`references/dependency-injection.md` for the full wiring pattern108(the Flutter team recommends `package:provider`; `get_it`/`injectable`109service-locator-style DI is a valid alternative if a repo already uses it —110the constructor-injection and privacy rules above still apply either way).111112## Workflow for building or reviewing a feature1131141. **Identify the feature** — it's exactly one View + one ViewModel pair.115 Name them `<Feature>Screen`/`<Feature>View` and `<Feature>ViewModel`.1162. **Identify the data types the feature needs.** Each distinct type of117 data gets (or reuses) its own `Repository` (e.g. `UserRepository`,118 `BookingRepository`). Don't let one repository own multiple unrelated119 data types, and don't let repositories know about each other — if two120 repositories' data needs to be combined, do that in the ViewModel or a121 use-case, not the repository.1223. **Identify the external sources the data comes from.** Each REST API,123 platform plugin, or local database gets its own `Service`124 (e.g. `ApiClient`, `SharedPreferencesService`). A repository composes125 one or more services.1264. **Write the ViewModel.** Constructor takes repositories/use-cases as127 required named parameters; expose UI state via public getters backed by128 private fields; expose actions as `Command` objects (see129 `references/design-patterns.md`); extend `ChangeNotifier` and call130 `notifyListeners()` whenever state changes.1315. **Write the View.** A widget whose only inputs are `key` and the132 ViewModel; wrap the parts that need to rebuild in `ListenableBuilder`133 (listening to the ViewModel or, for finer control, to an individual134 `Command`); forward taps/gestures straight to `viewModel.someCommand.execute(...)`.1356. **Wire dependency injection** at the app/router level — don't136 instantiate repositories or services inside widgets or view models.1377. **Consider error handling and loading state up front** using `Result`138 and `Command` (see `references/design-patterns.md`) rather than bolting139 them on later — almost every real ViewModel action needs a140 running/error/success representation.1418. **Write tests alongside the code**: unit tests for the ViewModel against142 a fake repository, unit tests for the repository against a fake service,143 and widget tests for the View. See `references/testing.md`.144145**Migrating existing code?** If you're converting a `StatefulWidget`/146`setState()` screen rather than starting fresh, follow147`references/migration.md` instead of starting at step 1 above — it walks the148same end state through incremental, compilable steps.149150**Auditing existing code for separation-of-concerns problems?** Scan it151against `references/audit-checklist.md` rather than rebuilding the workflow152above from scratch.153154## Recommended project structure155156```157lib/158 ui/159 core/ # shared widgets & themes used by multiple features160 ui/161 themes/162 <feature_name>/163 view_models/164 <feature>_view_model.dart165 widgets/166 <feature>_screen.dart167 <other widgets specific to this feature>168 domain/169 models/170 <model_name>.dart # domain models, shared by data + ui layers171 data/172 repositories/173 <repository_name>.dart174 services/175 <service_name>.dart176 model/177 <api_model_name>.dart # raw API/DB models, distinct from domain models178 config/179 utils/180 routing/181 main_development.dart182 main_staging.dart183 main.dart184185test/ # mirrors lib/ — unit + widget tests186testing/ # fakes and mocks shared across test files187 fakes/188 models/189```190191Notes on this structure (from the Flutter team, based on the Compass app):192- `data/` is organized **by type** (repositories, services) because those193 classes are reused across features.194- `ui/` is organized **by feature** because each feature owns exactly one195 View + ViewModel pair.196- `domain/models` holds the shared domain model classes, since both the197 data and UI layers depend on them.198- Multiple `main_*.dart` entry points support different environments199 (development/staging/production), typically wiring up different200 repository implementations (e.g. `BookingRepositoryRemote` vs201 `BookingRepositoryLocal`).202203## Non-negotiable rules when generating Flutter code204205Apply these unless the user has explicitly asked for a different pattern or206the surrounding codebase clearly already follows one:207208- **Never put business logic, network calls, or data mutation inside a209 widget's `build()` method or event handlers.** Only these are allowed210 directly in a View: simple if/else to show/hide widgets based on a flag211 from the ViewModel, animation logic, layout logic based on device info212 (screen size/orientation), and simple routing.213- **Never let a widget hold a `Repository` or `Service` reference.**214 Widgets only ever see a ViewModel.215- **Always make domain/UI-state data models immutable.** Prefer `freezed`216 (or `built_value`) for data classes so `copyWith`/equality/serialization217 are generated instead of hand-rolled.218- **Always expose ViewModel actions as methods that can be attached to219 event handlers** — prefer the `Command` pattern (see220 `references/design-patterns.md`) over ad-hoc `bool isLoading` /221 `String? error` fields duplicated per action.222- **Always make repositories, not services, the thing ViewModels depend223 on.** A ViewModel should never import an API client or a database224 service directly.225- **Always use dependency injection** (constructor injection, wired via226 `provider` or an equivalent mechanism like `get_it` at the widget-tree or227 router level) instead of singletons, global variables, or ad-hoc statics228 reached for from inside business logic.229- **Prefer `Result<T>`-returning methods over throwing exceptions** across230 service/repository/view-model boundaries so callers can't forget to231 catch (see `references/design-patterns.md`).232- **Write tests that exploit the architecture**: fake the repository to233 test a ViewModel, fake the service to test a repository. If a class is234 hard to fake or mock, that's a signal the class has too many235 responsibilities or unclear inputs/outputs.236237## Reference files — read these for implementation detail238239| File | Read when you need... |240|---|---|241| `references/ui-layer.md` | Full View/ViewModel code patterns, UI state, `ListenableBuilder` wiring, the Command pattern in context, and disposing ViewModels/Commands/subscriptions |242| `references/data-layer.md` | Full Repository/Service code patterns, domain vs. API models, the `Result` pattern in context |243| `references/dependency-injection.md` | Wiring everything together with `provider` + `go_router`, the full rules-of-engagement table |244| `references/migration.md` | Converting a `StatefulWidget`/`setState()` screen into View + ViewModel + Repository, step by step |245| `references/testing.md` | Unit-testing ViewModels/Repositories with fakes, widget-testing Views |246| `references/audit-checklist.md` | A quick-scan list of architecture smells for reviewing existing code against this skill's rules |247| `references/design-patterns.md` | Full `Command`/`Result` class implementations, Optimistic State, key-value persistence, SQL persistence, offline-first strategies |248| `references/recommendations.md` | The Flutter team's full prioritized do/don't tables, naming conventions, and recommended packages/resources |249250Load only the reference files relevant to the current task — don't read all251of them for a small, single-widget request.