/flutter:flutter-architecturefrom Flutter Skills
Enforces a feature-first layered MVVM architecture for Flutter apps using Riverpod 3.x. Features are folders; cross-cutting foundations become packages only when justified. Strict downward-only dependency DAG, dumb Views over one Notifier per feature, repositories as single source of truth, and abstractions only where something can't run in a test.
Ships in Flutter Skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them; scripts run unread.
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.
screens/, models/, or widgets/ bucket — those smear one feature across the
tree and force a name lookup on every edit.*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.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.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.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.load(), add(...)); every transition assigns a new immutable
value with value equality. No public setters, no mutable field the UI edits in place.Map never reaches a
ViewModel or widget; unit math and locale formatting never happen in a widget.DateTime.now() outside an injected
Clock. A composition root wires the object graph once.Result/Failure
rather than throwing across a layer; the UI switches exhaustively. See error-handling-typed-results.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/.
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.
A dumb View reads one ViewModel; the ViewModel holds private state and exposes intent methods.
// 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>> {
@override
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.
// features/tasks/task_list_screen.dart — the View is dumb: read one provider, render.
final class TaskListScreen extends ConsumerWidget {
const TaskListScreen({super.key});
@override
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).
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.
// 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.
Scale the architecture to the app. The three questions, in order:
flutter test, or you
genuinely swap dev/prod impls. Name the fake it enables.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: workspacewith one rootpubspec.lock; each package exposes one barrel (core.dart) over a privatesrc/— never import another package'ssrc/; the pure-Dartcorepackage declares noflutterdependency 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.
*UseCase / domain layer wrapping one repository call. Pure ceremony; a rename of the
repository method. Add the layer only when logic spans repositories.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.core.http/sqflite/SharedPreferences/a plugin called inside build() or initState(). Data
access belongs behind a repository, reached through a provider.count column next to the rows). It drifts. Derive
it from the source of truth.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.features/<x>/ or core/data location; grouping is feature-first.ConsumerWidget — no data access, no business logic, no formatting, no try/catch.Notifier/AsyncNotifier/StreamNotifier exposing immutable state + intent methods; no public setters, no notifyListeners() in the Riverpod path.Map type reaches a ViewModel or widget.DateTime.now() outside an injected clock.scripts/check_architecture.sh passes; dart analyze is clean.state-management-riverpod for the Notifier/AsyncNotifier API, watch/read/listen split, family+autoDispose, and stale-closure hazards.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.scaffold-feature-module for the step-by-step feature folder + typed go_router registration workflow.project-structure-and-packages for pubspec-as-audit-artifact, barrels, and one-way layering mechanics.app-startup-and-bootstrap for main() ordering, global error handlers, and DI overrides at the root.error-handling-typed-results for the sealed Result/Failure spine returned across boundaries.dart3-idioms-and-coding-standards for sealed types, exhaustive switches, and immutable value types.naming-conventions for the Screen/Notifier/Repository/Service/Failure role suffixes a grep can read.persistence-drift for the DAO/repository seam and transaction-per-mutation persistence.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:
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).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.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.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.examples/composition_root.dart (opens in a new tab)examples/feature_slice.dart (opens in a new tab)references/module-and-layers.md (opens in a new tab)references/right-sizing.md (opens in a new tab)references/state-di-riverpod.md (opens in a new tab)scripts/check_architecture.sh (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
40 skills in this plugin
/accessibility-as-codeEnforces accessibility as a correctness property authored into each widget — Semantics(button/label) or ExcludeSemantics on every node, a11y state read from MediaQuery not app state, never MediaQuery.withClampedTextScaling / textScaleFactor / FittedBox / TextOverflow.ellipsis to fit a label, non-color redundant channels (icon+label+shape+text) for every state, contrast against composited backgrounds (4.5:1 body / 3:1 large), 44px single-tap targets, OrdinalSortKey traversal, and honoring boldText / reduce-motion. Use when adding a GestureDetector/InkWell or any tap target, adding an Icon or Image, reaching for withClampedTextScaling/FittedBox/ellipsis/textScaleFactor to make text fit, encoding state via color, sizing type, ordering focus traversal, or reviewing any View for screen-reader/switch/low-vision support./adaptive-layoutEnforces adapting layout by available CONSTRAINTS/size, never device or platform checks — LayoutBuilder + MediaQuery.sizeOf/paddingOf/viewInsetsOf (not .of) for narrow rebuilds, Material 3 window size classes (compact <600, medium 600-840, expanded 840-1200, large >1200) as the breakpoint vocabulary, navigation affordance chosen by width (NavigationBar → NavigationRail → NavigationDrawer), list-detail single-pane-vs-two-pane, readable max-width via ConstrainedBox, Flexible/Expanded/FractionallySizedBox over fixed widths, SafeArea + display cutouts + keyboard insets, never lock orientation, foldable/hinge awareness via MediaQuery.displayFeatures, and golden-matrix verification across sizes. Use when building responsive or adaptive UI, tablet/desktop/foldable support, master-detail or two-pane screens, a NavigationRail-vs-BottomNav shell, breakpoints, LayoutBuilder, MediaQuery sizing, SafeArea/cutouts, or fixing overflow at large widths.npx claudepluginhub zakariaf/flutter-skills --plugin flutterOther plugins' skills for the same job