/flutter:navigation-and-routingfrom Flutter Skills
Enforces a single GoRouter in lib/routing/ with deep-linkable path params, context.go vs context.push discipline, pure redirect guards via Riverpod refreshListenable, StatefulShellRoute for bottom-nav/rail shells, CustomTransitionPage, PopScope, and errorBuilder 404.
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.
This skill owns app navigation with go_router. There is exactly ONE GoRouter for the app, defined in lib/routing/, and every screen is reachable by a URL. Navigation is a data structure (routes + a pure redirect), not a pile of imperative Navigator.push calls.
Read the reference for the task at hand:
references/go-router-config.md — the single router, context.go vs context.push, path params vs state.extra, typed route helpers, errorBuilder/404.references/guards-and-redirects.md — pure redirect functions, the Riverpod refreshListenable, auth + onboarding gates, avoiding redirect loops.references/shells-and-deep-links.md — StatefulShellRoute.indexedStack for bottom-nav/rail shells, CustomTransitionPage, PopScope, and notification-payload → location mapping.Run scripts/check_routing.sh before a PR.
GoRouter, built in lib/routing/, wired once via MaterialApp.router in app.dart. Multiple routers fragment history, deep links, and back-button behaviour. The router is created behind a provider so guards can watch app state.state.extra. extra is a live Dart object: it is null on a cold start from a deep link and after process death / restoration. A screen that needs an id to rebuild must read it from state.pathParameters so the URL alone fully reconstructs the screen.state.extra is ONLY an optional non-identity optimisation (a pre-fetched object to avoid a reload flash). The screen must still work — refetch by id — when extra is null.context.go to replace the stack (declarative destinations, tabs, post-login home); use context.push to stack a screen you expect to pop back from (a detail, a modal flow). Mixing them wrong breaks the back button. Know which one every call site needs.redirect functions. redirect returns a new location String? (or null to allow) from GoRouterState + a snapshot of app state. No I/O, no navigation calls, no side effects inside redirect — it runs on every navigation and can run repeatedly.refreshListenable, not polling. Bridge the Riverpod auth/onboarding provider to a Listenable; the router re-evaluates redirect whenever it fires. See state-management-riverpod./sign-in back to /sign-in). Guard against A→B→A by checking the current location before redirecting.StatefulShellRoute.indexedStack. It preserves each branch's navigation stack and state across tab switches; a plain ShellRoute with an IndexedStack you wire by hand does not survive router rebuilds as cleanly. Switch branches with navigationShell.goBranch(index).CustomTransitionPage and respect reduced motion. When the platform requests reduced motion, collapse to a no-op/fade. Read the flag from MediaQuery, resolve motion via the design system — see accessibility-as-code and design-system-structure.PopScope, not WillPopScope (removed). Set canPop: false and handle in onPopInvokedWithResult(bool didPop, T? result); only navigate away after the user confirms.errorBuilder and a real 404/error route. An unmatched deep link must land on a designed error screen, never a red error box.BuildContext across an await before navigating. Capture GoRouter.of(context) (or the router) before the await, or guard with context.mounted after. See async-safety.scaffold-feature-module registers a feature's GoRoute INTO this router's route list; features never instantiate GoRouter.app.dart reads the router from a provider and hands it to MaterialApp.router. The router itself lives in routing/ and is the only place GoRouter(...) is constructed.
// routing/app_router.dart
final routerProvider = Provider<GoRouter>((ref) {
// Bridge Riverpod auth state to a Listenable the router can watch.
final refresh = ValueNotifier<int>(0);
ref.onDispose(refresh.dispose);
ref.listen(authNotifierProvider, (_, __) => refresh.value++);
return GoRouter(
initialLocation: Routes.home,
refreshListenable: refresh,
redirect: (context, state) => appRedirect(ref.read(authNotifierProvider), state),
errorBuilder: (context, state) => ErrorScreen(error: state.error),
routes: $appRoutes, // assembled from feature route lists
);
});
// app.dart — the only MaterialApp.router
class MyApp extends ConsumerWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final router = ref.watch(routerProvider);
return MaterialApp.router(
routerConfig: router,
theme: lightTheme,
darkTheme: darkTheme,
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
);
}
}
// GOOD: id is in the URL — a cold-start deep link to /items/42 fully rebuilds.
GoRoute(
path: '/items/:id',
builder: (context, state) {
final id = state.pathParameters['id']!; // always present
// extra is an OPTIONAL fast-path; screen must work when it is null.
final preloaded = state.extra as Item?;
return ItemScreen(itemId: id, preloaded: preloaded);
},
),
// BAD: identity smuggled through extra — null on cold start / after process death.
context.push('/item', extra: item); // no id in the URL => not deep-linkable
Prefer small constant/builder classes so call sites never hand-concatenate paths. go_router_builder codegen is an OPTIONAL upgrade, not the default.
// routing/routes.dart
abstract final class Routes {
static const home = '/';
static const items = '/items';
static String item(String id) => '/items/$id';
static const signIn = '/sign-in';
}
// call site
context.push(Routes.item(item.id));
context.go(Routes.home); // replace whole stack: post-login, tab roots
context.push(Routes.item(id)); // stack a detail you'll pop back from
context.pop(result); // return up, optionally with a result
GoRouter instances, or a nested Navigator/MaterialApp inside a screen for "sub-navigation." Use nested routes / StatefulShellRoute.state.extra and reading extra! in build — crashes on cold start.ref.read of async work, or calling context.go INSIDE redirect. Redirect is pure and returns a location.redirect that can bounce forever because it also redirects its own target.Navigator.pushNamed('/x') string routes with go_router — one navigation system only.WillPopScope (removed) instead of PopScope.context to navigate without a mounted check.GoRouter.GoRouter in lib/routing/, one MaterialApp.router in app.dart.state.pathParameters.state.extra is only ever an optional optimisation; every such screen renders correctly with extra == null.redirect functions with a refreshListenable; no redirect loops.StatefulShellRoute.indexedStack; branch state survives tab switches.errorBuilder + 404 route present.PopScope guards unsaved changes; no BuildContext used across an await when navigating.scripts/check_routing.sh passes.app-startup-and-bootstrap — owns main()/bootstrap() ordering and where MaterialApp.router is mounted.state-management-riverpod — the auth/onboarding providers the refreshListenable bridges.scaffold-feature-module — registers a feature GoRoute into this router.adaptive-layout — chooses NavigationRail vs BottomNavigationBar by width for the shell.accessibility-as-code — reduced-motion flag and semantics for navigation.design-system-structure — the reduced-motion token / resolveMotion helper for transitions.async-safety — BuildContext/mounted rules around awaited navigation.local-notifications-scheduler — the notification payload whose pure mapper produces a location.examples/app_router.dart (opens in a new tab)examples/auth_redirect.dart (opens in a new tab)examples/shell_scaffold.dart (opens in a new tab)references/go-router-config.md (opens in a new tab)references/guards-and-redirects.md (opens in a new tab)references/shells-and-deep-links.md (opens in a new tab)scripts/check_routing.sh (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
go_router, deep-links, redirect-guards, shell-routes, page-transitions, pop-scope
npx claudepluginhub zakariaf/flutter-skills --plugin flutter40 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./ads-and-iap-monetizationEnforces opt-in, rewarded-first monetization over the service seam — a rewarded view grants exactly one benefit and only on a genuine reward outcome (a sealed Rewarded/Dismissed/NoFill), earn loops capped per day against an injected Clock, the earn control preloaded and hidden unless an ad is loaded so a fresh account never dead-ends on "no ads available" (a Guideline 2.1 risk), interstitials only at a natural break under a count-and-elapsed cap owned by the service so callers stay dumb, no banner on the primary work surface, one non-consumable unlock plus Restore re-checked each launch and committed through the single write path before the UI reacts, one derived isEntitled provider as the only gate, and the entitlement restored BEFORE the ad SDK initializes so a paying user never starts it, resolves consent, or sees a tracking prompt. Use when adding ads, wiring a rewarded earn loop, placing an interstitial, building a paywall, gating an entitlement, or setting up ad units./app-startup-and-bootstrapEnforces a fixed main() cold-launch order — crash-log sink + FlutterError.onError + PlatformDispatcher.onError installed BEFORE any code that can throw, settings/theme read before runApp so the first frame paints correct, real infra constructed in a composition-root bootstrap() and injected via ProviderScope overrideWithValue over throwing placeholder providers, non-blocking warm-up deferred to addPostFrameCallback, exactly two error handlers with NO runZonedGuarded, ProviderException unwrapped before logging, and a WidgetsBindingObserver that flushes durable state on background/resume. Use when editing lib/main.dart, main_<flavor>.dart, bootstrap.dart or app.dart, reordering anything in main(), adding a splash/onboarding/permission gate, restoring theme before first paint, wiring a DB or service into ProviderScope, handling app-lifecycle background/resume flushes, or chasing cold-start latency, ANRs, or first-frame jank./async-safetyEnforces no-silent-failure async discipline in Flutter/Dart — the arrow-callback Future-drop hole no lint catches (`onTap: () => vm.save(x)`), void-returning event handlers, a mounted/ref.mounted guard after EVERY await before touching BuildContext, capturing Navigator/ScaffoldMessenger before the gap, honest `unawaited()` that always ends in catchError, no empty/bare catches, `rethrow` over `throw e`, and disposing every StreamSubscription/StreamController/Timer/sink. Use when writing or reviewing async/await, wiring onTap/onPressed/onSubmitted or any VoidCallback, touching BuildContext after an await, writing initState/dispose/addPostFrameCallback, adding a Timer or Future.delayed, writing a try/catch, or seeing use_build_context_synchronously, cancel_subscriptions, close_sinks, unawaited_futures, or discarded_futures./ci-pipeline-and-gatesEnforces a lean GitHub Actions Flutter CI where every gate maps to one named release-blocking contract — pinned runner + subosito/flutter-action@v2 toolchain, dart format --set-exit-if-changed, flutter analyze --fatal-infos, build_runner and drift schema freshness (git diff --exit-code), flutter test --test-randomize-ordering-seed random, static import/banned-string greps that catch what runtime can't, coverage-as-report-never-a-gate with the upward-lie fixed, verify-never-bless goldens (no --update-goldens in CI), and an honest statement of what CI cannot prove (audio, real fonts, on-device behaviour). Use when editing .github/workflows/*.yml, adding or removing a job or step, wiring a codegen/schema/format/analyze/coverage gate, writing a grep-based policy test or gate script under test/policy or tool/, pinning action versions, or claiming CI proves something it can't.Other plugins' skills for the same job