# Playx Navigation > Playx Navigation (`playx_navigation`, version 3.0.0) is a Flutter package built on go_router. It adds a per-page lifecycle (onEnter, onHidden, onReEnter, onExit) for every route, page-scoped controllers, route guards, web-friendly navigation (back to parent, popUntil, breadcrumbs, browser tab titles) and navigation without a BuildContext. It re-exports go_router, so `import 'package:playx_navigation/playx_navigation.dart';` is enough. Key facts for code generation: - Requirements: Flutter >=3.27.0, Dart >=3.6.0, go_router ^17.5.0 (re-exported). - Use `PlayxRoute` instead of `GoRoute` and `PlayxShellBranch` for tabs. Both accept `binding`, `controller`, `disposeController`, `guards`, `breadcrumb`, `parentLocation`, `loadingWidget`, `shellBuilder`, `waitForBinding`, `initTransitionDuration`, `errorBuilder`, `enterTimeout`, `transition`, `pageConfiguration`. Provide exactly one of `builder` or `initBuilder`. - Wrap the app in `PlayxNavigationBuilder(router: router, builder: (context) => MaterialApp.router(routerConfig: router))`. This boots navigation and runs every binding's `onInitApp`. Without it call `await PlayxNavigation.boot(router: router)`. - A `PlayxBinding` must implement `onEnter(BuildContext, GoRouterState)`. `onInitApp`, `onHidden`, `onReEnter(context, state, wasPoppedAndReentered)`, `onExit`, `redirect` and `breadcrumb` are optional. - The lifecycle belongs to each page instance (not each route): stacked pages of the same route each get their own onEnter/onExit. On pop, the revealed page gets onReEnter immediately and the popped page gets onExit after the exit animation. Replace or a changed path parameter ends the old page's lifecycle before the new onEnter. - `PlayxScope.of(context)` returns the page's scope (unique `id`, `put`/`get`, `onDispose`). Use `scope.id` as a GetX tag so stacked pages do not share controllers. - Route controllers: `PlayxRoute(controller: (context, state) => MyController(), disposeController: (c) => c.onClose(), builder: ...)`. Views extend `PlayxView` and implement `buildView(context, controller)`, or use `context.controller()`. Controllers can mix in `PlayxPageLifecycle` (onPageEnter, onPageHidden, onPageReEnter, onPageExit). - Navigate with the static `PlayxNavigation`: `to`, `toNamed` (push), `offAll`, `offAllNamed` (go, replaces the stack), `offAndTo`, `offAndToNamed` (replace the top page; the returned Future completes when the new page is popped, so do not await it just to wait for navigation), `pop`, `maybePop`, `back`, `popOrGo`, `popUntil`, `goToBranch`. - On web `state.extra` is null after refresh or deep links: load by id. Use `state.extraAs()`, `state.intPathParam('id')`, `state.intQueryParam('page')`. Use `PlayxNavigation.back()` / `PlayxBackButton` so back works when nothing can be popped. - Breadcrumbs: label routes with `breadcrumb: (context, state) => 'Label'`, show them with `PlayxBreadcrumbs(mode: PlayxBreadcrumbMode.hierarchy | shellBranch | history)`. Browser tab titles: `PlayxNavigationBuilder(pageTitle: PlayxPageTitle(appName: '...'))`. - Redirect order for a route: `guards` (PlayxGuard), then the binding's `redirect`, then the route's `redirect`. - Do not call `PlayxNavigation` before boot, and do not await `offAndTo` expecting it to finish when the replacement happens. --- The full documentation follows. --- # Playx Navigation **Playx Navigation** is a navigation package for Flutter built on top of [`go_router`](https://pub.dev/packages/go_router). It keeps everything go_router gives you and adds what larger apps keep rebuilding by hand: - a **lifecycle for every page** (`onEnter`, `onHidden`, `onReEnter`, `onExit`) that behaves correctly with shell routes, stacked pages, deep links, replace and the browser's back button; - **page-scoped state**: controllers that are created per page, can't overwrite each other, and are disposed when the page goes away, with optional GetX interop; - **web-friendly navigation**: back to the parent when there is nothing to pop, `popUntil`, breadcrumbs, and browser tab titles; - **navigation without a `BuildContext`**, route guards, error handling for slow or failing page setup, and loading states without blank frames. ```dart PlayxRoute( path: ':id', breadcrumb: (context, state) => 'Job #${state.pathParameters['id']}', controller: (context, state) => JobDetailsController(state.intPathParam('id')!), disposeController: (controller) => controller.onClose(), builder: (context, state) => const JobDetailsView(), ) class JobDetailsView extends PlayxView { const JobDetailsView({super.key}); @override Widget buildView(BuildContext context, JobDetailsController controller) { return Scaffold(body: Text(controller.title)); } } ``` ## Where to go next | I want to... | Read | |---|---| | Add the package to an app | [Installation and setup](getting-started.md) | | Decide between bindings, scopes and route controllers | [Choosing an approach](choosing-an-approach.md) | | Define routes, transitions and shell branches | [Routes and transitions](routes.md) | | Understand exactly when `onEnter` / `onExit` run | [Bindings and lifecycle](bindings.md) | | Show loading states, shells and animations | [Page configuration](page-configuration.md) | | Protect routes, validate parameters | [Guards and redirects](guards-and-redirects.md) | | Handle slow or failing page setup | [Error handling](error-handling.md) | | Keep a controller per page (GetX, Bloc, ...) | [Scopes](scopes.md), [Route controllers and views](controllers-and-views.md) | | Navigate from anywhere in the app | [PlayxNavigation API](navigation-api.md) | | Support web refresh, deep links, tab titles | [Web](web.md), [Breadcrumbs and page titles](breadcrumbs.md) | | Test my bindings and controllers | [Testing your app](testing.md) | | Upgrade from 2.x | [Migrating to 3.0](migration.md) | ## Requirements - Flutter `>=3.27.0`, Dart `>=3.6.0` - `go_router` `^17.5.0` (re-exported by this package, so one import is enough) ## Links - [pub.dev](https://pub.dev/packages/playx_navigation) - [GitHub](https://github.com/playx-flutter/playx_navigation) - [API reference](https://playx-flutter.github.io/playx_navigation/api/) - [`llms.txt`](llms.txt) and [`llms-full.txt`](llms-full.txt) for AI assistants --- # Installation and setup ## Install ```yaml dependencies: playx_navigation: ^3.0.0 ``` ```bash flutter pub get ``` `playx_navigation` re-exports `go_router`, so a single import gives you both: ```dart import 'package:playx_navigation/playx_navigation.dart'; ``` ## 1. Define route names and paths (optional) ```dart abstract class Routes { static const home = 'home'; static const products = 'products'; static const productDetails = 'productDetails'; } abstract class Paths { static const home = '/home'; static const products = '/products'; static const productDetails = ':id'; // relative: /products/:id } ``` ## 2. Create bindings A binding attaches logic to a route's lifecycle. `onEnter` is the only method you must implement; the rest are optional. See [Bindings and lifecycle](bindings.md) for the full contract. ```dart class ProductsBinding extends PlayxBinding { @override Future onInitApp() async { // Once, at boot, before any page is entered: register repositories, services... } @override Future onEnter(BuildContext context, GoRouterState state) async { // The page is about to be shown for the first time: load data, create controllers. } @override Future onExit(BuildContext context) async { // The page was removed: release resources. } } ``` > **No binding needed?:** For a page that only needs one controller you can skip the binding entirely and use a > [route controller](controllers-and-views.md). See > [Choosing an approach](choosing-an-approach.md). ## 3. Build the router with `PlayxRoute` `PlayxRoute` extends go_router's `GoRoute`, so it works anywhere a `GoRoute` does (including inside `StatefulShellRoute` and `ShellRoute`). ```dart final router = GoRouter( initialLocation: Paths.home, routes: [ PlayxRoute( path: Paths.home, name: Routes.home, builder: (context, state) => const HomePage(), binding: HomeBinding(), ), PlayxRoute( path: Paths.products, name: Routes.products, builder: (context, state) => const ProductsPage(), binding: ProductsBinding(), routes: [ PlayxRoute( path: Paths.productDetails, name: Routes.productDetails, builder: (context, state) => ProductDetailsPage(product: state.extraAs()), binding: ProductDetailsBinding(), ), ], ), ], ); ``` ## 4. Wrap your app in `PlayxNavigationBuilder` `PlayxNavigationBuilder` boots the navigation system: it finds every binding in the route tree, runs each `onInitApp`, and provides global configuration to the pages. ```dart class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return PlayxNavigationBuilder( router: router, config: const PlayxPageConfig( loadingWidget: Center(child: CircularProgressIndicator()), ), builder: (context) => MaterialApp.router(routerConfig: router), ); } } ``` > **Booting without the widget:** You can call `await PlayxNavigation.boot(router: router)` yourself (for example before > `runApp`) and omit `router:` from the builder. `await PlayxNavigation.ensureInitialized` > completes once every `onInitApp` has finished. ## 5. Navigate from anywhere ```dart PlayxNavigation.toNamed(Routes.productDetails, pathParameters: {'id': '5'}, extra: product); PlayxNavigation.back(); ``` No `BuildContext` is needed. See the [PlayxNavigation API](navigation-api.md). ## Web setup Call this before `runApp` to use path URLs and have the browser URL reflect `push`: ```dart void main() { PlayxNavigation.setupWeb(); runApp(const MyApp()); } ``` See [Web](web.md) for refresh, deep links, back buttons and tab titles. --- # Choosing an approach Playx Navigation offers three ways to attach logic and state to a page. They can be mixed in the same app, even on the same route. | | 1. Binding only | 2. Binding + scope | 3. Route controller | |---|---|---|---| | You write | a `PlayxBinding` class | a `PlayxBinding` class | one `controller:` factory on the route | | Controller lives in | wherever you put it (a global registry, a field) | the page's [`PlayxScope`](scopes.md) or a registry keyed by `scope.id` | the page's `PlayxScope` (optionally mirrored into GetX) | | Safe with the same route stacked twice | only if you key by hand | yes | yes | | Views read it with | `Get.find`, `Provider`, ... | `PlayxView` / `context.controller()` / `Get.find(tag:)` | `PlayxView` / `context.controller()` | | Lifecycle hooks | binding methods | binding methods | `PlayxPageLifecycle` mixin on the controller (and binding methods if you also add a binding) | | Best for | app-level setup (`onInitApp`), redirects, several resources per page | pages needing async setup or several controllers | the common "one controller per page" case | ## Decision guide - **A page needs one controller and a view that uses it** → route controller ([guide](controllers-and-views.md)). - **A page needs async setup, several controllers, or special cleanup** → binding with a scope ([guide](scopes.md)). - **You only need to register app-wide services at startup, or validate parameters** → a binding's `onInitApp` / `redirect`. - **The page has no state at all** → a plain `PlayxRoute` without binding or controller. ## The same page three ways **Binding only** ```dart class JobsBinding extends PlayxBinding { @override Future onEnter(BuildContext context, GoRouterState state) async { Get.put(JobsController()); } @override Future onExit(BuildContext context) async { Get.delete(); } } PlayxRoute(path: '/jobs', binding: JobsBinding(), builder: (_, __) => const JobsView()); ``` Simple, but two stacked pages of the same type share one registration. **Binding + scope** ```dart class JobsBinding extends PlayxBinding { @override Future onEnter(BuildContext context, GoRouterState state) async { Get.put(JobsController(), tag: PlayxScope.of(context).id); } @override Future onExit(BuildContext context) async { Get.delete(tag: PlayxScope.of(context).id); } } ``` The tag is unique per page, so stacked pages get their own controller. **Route controller** ```dart PlayxRoute( path: '/jobs', controller: (context, state) => JobsController(), disposeController: (controller) => controller.onClose(), builder: (_, __) => const JobsView(), // a PlayxView ) ``` No binding class. The package creates, scopes and disposes the controller. --- # Routes and transitions ## `PlayxRoute` `PlayxRoute` extends go_router's `GoRoute`. Everything `GoRoute` supports still works (`path`, `name`, `parentNavigatorKey`, `redirect`, `onExit`, nested `routes`); it adds lifecycle, state and web features. ```dart PlayxRoute( path: ':id', name: 'jobDetails', // Content: provide exactly one of builder / initBuilder. builder: (context, state) => const JobDetailsView(), // Lifecycle and state (all optional): binding: JobDetailsBinding(), controller: (context, state) => JobDetailsController(state.intPathParam('id')!), disposeController: (controller) => controller.onClose(), // Navigation behavior: transition: PlayxPageTransition.fade, pageConfiguration: const PlayxPageConfiguration(fullscreenDialog: true), guards: [const AuthGuard()], parentLocation: (state) => '/jobs', breadcrumb: (context, state) => 'Job #${state.pathParameters['id']}', // Loading behavior (see Page configuration): loadingWidget: const Center(child: CircularProgressIndicator()), shellBuilder: (context, state, isInitialized, child) => Scaffold(body: child), waitForBinding: false, initTransitionDuration: const Duration(milliseconds: 200), // Failures: errorBuilder: (context, state, error, stackTrace, retry) => ErrorView(onRetry: retry), enterTimeout: const Duration(seconds: 10), ) ``` | Parameter | Purpose | Docs | |---|---|---| | `builder` / `initBuilder` | Page content. `initBuilder` also receives `isInitialized`. | [Page configuration](page-configuration.md) | | `binding` | Lifecycle callbacks, `redirect`, `breadcrumb`. | [Bindings](bindings.md) | | `controller`, `disposeController` | One controller per page visit. | [Route controllers](controllers-and-views.md) | | `transition`, `pageConfiguration` | How the page animates and behaves as a route. | below | | `guards` | Redirect before the route is entered. | [Guards](guards-and-redirects.md) | | `parentLocation` | Where `back()` goes when nothing can be popped. | [Web](web.md) | | `breadcrumb` | The route's breadcrumb label. | [Breadcrumbs](breadcrumbs.md) | | `loadingWidget`, `shellBuilder`, `waitForBinding`, `initTransitionDuration` | Loading states. | [Page configuration](page-configuration.md) | | `errorBuilder`, `enterTimeout` | Slow or failing page setup. | [Error handling](error-handling.md) | Exactly one of `builder` or `initBuilder` is required (asserted in debug mode). ## Shell routes `PlayxShellBranch` is a `StatefulShellBranch` with one `PlayxRoute` inside. It takes the same parameters as `PlayxRoute`, so a tab and its child pages are easy to declare: ```dart StatefulShellRoute.indexedStack( builder: (context, state, navigationShell) => AppScaffold(shell: navigationShell), branches: [ PlayxShellBranch( path: '/jobs', name: 'jobs', breadcrumb: (context, state) => 'Jobs', builder: (context, state) => const JobsView(), binding: JobsBinding(), routes: [ PlayxRoute( path: ':id', builder: (context, state) => const JobDetailsView(), binding: JobDetailsBinding(), ), ], ), PlayxShellBranch( path: '/settings', builder: (context, state) => const SettingsView(), ), ], ) ``` For a branch with several top-level routes use `PlayxShellBranch.routes(routes: [...])`. Branch constructor options such as `navigatorKey`, `initialLocation`, `observers` and `preload` are available too. Switch tabs with `PlayxNavigation.goToBranch(index: 1, navigationShell: shell)`. Pages in other branches stay alive and receive `onHidden` / `onReEnter`, never `onExit` ([details](bindings.md#shell-routes)). Plain `ShellRoute` works as well: its pages are removed on navigation, so they exit normally. ## Transitions `transition` takes a `PlayxPageTransition`: | Value | Effect | |---|---| | `cupertino` (default) | iOS-style slide. | | `material` | Material page transition. | | `native` | Cupertino on iOS and macOS, Material elsewhere. | | `fade` | Cross-fade. | | `none` | No animation. | | `custom` | Your `transitionsBuilder` from `PlayxPageConfiguration.customTransition`. | ```dart PlayxRoute( path: '/details', transition: PlayxPageTransition.custom, pageConfiguration: PlayxPageConfiguration.customTransition( transitionsBuilder: (context, animation, secondaryAnimation, child) => SlideTransition( position: Tween(begin: const Offset(0, 1), end: Offset.zero).animate(animation), child: child, ), transitionDuration: const Duration(milliseconds: 250), reverseTransitionDuration: const Duration(milliseconds: 200), opaque: true, ), builder: (context, state) => const DetailsPage(), ) ``` ### `PlayxPageConfiguration` | Field | Meaning | |---|---| | `key`, `name`, `arguments`, `restorationId` | Passed to the underlying `Page`. `key` defaults to the page key from go_router. | | `maintainState` | Keep the page built while it is covered (default `true`). If `false`, its widgets are disposed while covered, which ends its lifecycle (`onHidden`, `onExit`) and starts a new one (`onEnter`) when it is revealed again. | | `fullscreenDialog` | Present as a fullscreen dialog. | | `canPop`, `onPopInvoked` | Control and observe popping (`PopScope`-style). | | `transitionsBuilder`, `transitionDuration`, `reverseTransitionDuration` | Only for `custom` (and durations also for `fade`). | | `opaque`, `barrierDismissible`, `barrierColor`, `barrierLabel` | Route opacity and barrier for `custom` and `fade`. | > **Note:** `none` ignores durations and barrier options. `fade` uses the configuration's durations. --- # Bindings and lifecycle A `PlayxBinding` attaches logic to a route. Every page that shows a route with a binding runs the binding's callbacks at well-defined moments. ```dart class JobsBinding extends PlayxBinding { @override Future onInitApp() async {} // once, at boot @override FutureOr redirect(BuildContext c, GoRouterState s) => null; // before the page is built @override Future onEnter(BuildContext c, GoRouterState s) async {} // required @override Future onHidden(BuildContext c) async {} @override Future onReEnter(BuildContext c, GoRouterState? s, bool popped) async {} @override Future onExit(BuildContext c) async {} @override String? breadcrumb(BuildContext c, GoRouterState s) => null; // see Breadcrumbs } ``` Only `onEnter` is required. `context` is the page's own context. `PlayxScope.of(context)` returns the page's [scope](scopes.md) in every callback, including `onExit`. ## The callbacks | Callback | When | Typical use | |---|---|---| | `onInitApp()` | Once per binding, during boot, before any page enters. | Register repositories, datasources, services. | | `redirect(context, state)` | Before the route is built, when it is the destination (not for child routes). Return a location to redirect or `null`. | Validate parameters (`/jobs/abc`). | | `onEnter(context, state)` | The page is shown for the first time. | Load data, create controllers. | | `onHidden(context)` | Another page covers this one (push, tab switch) but it stays in the stack. | Pause timers, dismiss tours. | | `onReEnter(context, state, wasPoppedAndReentered)` | The page becomes visible again after being hidden. | Refresh, resume. | | `onExit(context)` | The page is removed from the tree. | Dispose resources. | `wasPoppedAndReentered` is `true` when the pages above it were removed (pop, `popUntil`, `go` to a parent, resetting a branch), and `false` when it comes back through a branch switch. ### Order ``` onInitApp -> onEnter -> onHidden <-> onReEnter -> onHidden -> onExit ``` `onExit` is always preceded by `onHidden` unless the page was never entered or is replaced in place (see below). ## Guarantees These hold for every navigation, so bindings can rely on them. - **One lifecycle per page, not per route.** `details/1` pushed over `details/2` are two pages; the first receives `onHidden` and later `onReEnter`. The same applies when a single binding instance is shared by several routes. - **Callbacks never overlap.** For one page they run strictly in order. Leaving a page while `onEnter` is still running queues `onHidden` / `onExit` until it finishes, so cleanup always runs after setup. - **Leaving before entering.** On one navigation, every `onHidden` starts before any `onEnter` / `onReEnter`. - **`onExit` follows the exit animation.** When a page is popped, the revealed page gets `onReEnter` immediately; the popped page gets `onHidden` immediately and `onExit` once it is removed from the tree. - **`onEnter` waits for `onInitApp`.** No page enters before every binding's `onInitApp` finished. If boot fails the page is not entered (it shows the [error handling](error-handling.md)). - **Replace and parameter changes start a new lifecycle.** `PlayxNavigation.offAndTo(...)`, or going from `/item/1` to `/item/2`, ends the old page's lifecycle (`onExit` completes) before the new page's `onEnter` starts, and `onEnter` receives the new parameters. Query-only changes do not restart it. - **Deep links and preloaded branches are pending.** A page mounted behind the visible page (the parent of a deep-linked child, or a `preload: true` shell branch) has `PlayxPageState.pending`. It receives `onEnter` (not `onReEnter`) when it is first shown. - **A failed `onEnter` is not entered.** If it throws or times out, no `onHidden` / `onReEnter` / `onExit` runs for that page. Nothing is left half-initialized. - **Only router navigation counts.** Dialogs, bottom sheets and routes pushed with `Navigator.push` (outside go_router) do not hide the page underneath. ## Shell routes ``` Branch A (Home) <-> Branch B (Products) 1. Enter Home home.onEnter 2. Switch to Products home.onHidden, products.onEnter 3. Switch back products.onHidden, home.onReEnter(popped: false) ``` ``` Parent -> child (push and pop) 1. Enter list list.onEnter 2. Push details list.onHidden, details.onEnter 3. Pop details details.onHidden, list.onReEnter(popped: true), details.onExit 4. Navigate away list.onHidden, list.onExit ``` ### Scenario table Shell with `products -> details` and `favorites -> details` branches, plus a top-level `/details/:id` route: | Navigation | Events | |---|---| | Products, push details | `products.onHidden`, `details.onEnter` | | Pop details | `details.onHidden`, `products.onReEnter(popped: true)`, `details.onExit` | | Favorites details, switch to the products tab | `favDetails.onHidden`, `products.onReEnter(popped: false)` | | Switch back to favorites | `products.onHidden`, `favDetails.onReEnter(popped: false)` | | Push top-level `/details/1` from anywhere, then pop | `origin.onHidden`, `details.onEnter`, then `details.onHidden`, `origin.onReEnter(popped: true)`, `details.onExit` | | `go('/products/details/7')` from favorites details | `favDetails.onHidden`, `details.onEnter` (favorites details stays alive in its branch) | | Deep link to `/products/details/1`, then pop | `details.onEnter`, then `products.onEnter` (not re-enter) | | `goBranch(i, initialLocation: true)` with details open | `details.onHidden`, `products.onReEnter(popped: true)`, `details.onExit` | | `go('/login')` (outside the shell) | `onExit` once for every page that was entered, in every branch | ## Page state `binding.currentState` (a `PlayxPageState?`) reflects the page's phase: `pending`, `enter`, `reEnter`, `hidden`, `exit`. It is shared by every page using the binding, so for several live pages prefer `PlayxScope.of(context).pageState`. ## Sharing a binding between live pages One binding instance can back several pages that are alive at the same time (the same route stacked, or one instance used for several routes). Each page still gets its own `onEnter` / `onExit`, so one page's `onExit` can run while another page of that binding is active, and for different routes the new page's `onEnter` can run before the old page's `onExit`. Keep per-page state in the page's [scope](scopes.md), or check `binding.activeScopes`: ```dart @override Future onExit(BuildContext context) async { // activeScopes no longer contains this page here. if (activeScopes.isEmpty) Get.delete(); } ``` ## Binding registry ```dart final binding = PlayxNavigation.findBinding(); // throws if not found final maybe = PlayxNavigation.findBindingOrNull(); final all = PlayxNavigation.bindings; // unmodifiable ``` Bindings are collected from the route tree during boot, including nested and shell routes. ## Binding redirect `redirect` validates before the page is built, which is better than navigating away from `onEnter` (the page would still be built with missing data): ```dart @override FutureOr redirect(BuildContext context, GoRouterState state) => state.intPathParam('id') == null ? '/jobs' : null; ``` It runs after the route's `guards` and before the route's own `redirect`, and only when the binding's own route is the destination. See [Guards and redirects](guards-and-redirects.md). --- # Page configuration While a binding's `onEnter` runs, the page can show a loading state. These options decide what the user sees. Settings can be given per route or once for all routes with `PlayxPageConfig`. ## Resolution order For every option: **route value, then global `PlayxPageConfig`, then the built-in default.** ```dart PlayxNavigationBuilder( router: router, config: PlayxPageConfig( loadingWidget: const Center(child: CircularProgressIndicator()), waitForBinding: true, initTransitionDuration: const Duration(milliseconds: 200), shellBuilder: (context, state, isInitialized, child) => Scaffold(body: child), ), builder: (context) => MaterialApp.router(routerConfig: router), ) ``` | Option | Route | Global | Default | |---|---|---|---| | Loading widget | `loadingWidget` | `PlayxPageConfig.loadingWidget` | `SizedBox.shrink()` | | Block until `onEnter` completes | `waitForBinding` | `PlayxPageConfig.waitForBinding` | `true` | | Shell around the content | `shellBuilder` | `PlayxPageConfig.shellBuilder` | none | | Cross-fade loading to content | `initTransitionDuration` | `PlayxPageConfig.initTransitionDuration` | none | | Error UI | `errorBuilder` | `PlayxPageConfig.errorBuilder` | none (see [Error handling](error-handling.md)) | | `onEnter` timeout | `enterTimeout` | `PlayxPageConfig.enterTimeout` | none | These options apply to routes that have a binding or a controller. A route without either has nothing to wait for and builds immediately. ## Blocking (default) The page shows `loadingWidget` until `onEnter` finishes, then the content. This guarantees the content never builds before its data and controllers exist. ## Non-blocking: `waitForBinding: false` The content builds immediately and `onEnter` runs in the background. Use it when the page can render before data arrives (skeletons, placeholders). ```dart PlayxRoute( path: '/profile', binding: ProfileBinding(), waitForBinding: false, builder: (context, state) => const ProfilePage(), ) ``` > **Note:** A page with a [route controller](controllers-and-views.md) always waits until the controller > exists, even with `waitForBinding: false`, so a view never builds without its controller. ## Shell builder A `shellBuilder` renders the page's chrome (AppBar, Drawer, Scaffold) **immediately**, including during the page transition. Only the body waits for `onEnter`, so there are no blank frames. ```dart PlayxRoute( path: '/channels', binding: ChannelsBinding(), builder: (context, state) => const ChannelsList(), // the body shellBuilder: (context, state, isInitialized, child) => Scaffold( appBar: AppBar(title: const Text('Channels')), drawer: isInitialized ? const AppDrawer() : null, body: child, // loading widget until initialized, then the body ), ) ``` `child` is the loading widget until `onEnter` completes, then the result of `builder`. `shellBuilder` only applies with `builder`, not `initBuilder`. ## Init-aware builder `initBuilder` gives you full control: it receives `isInitialized` and decides what to show. The loading widget, shell builder and cross-fade are not applied. ```dart PlayxRoute( path: '/profile', binding: ProfileBinding(), initBuilder: (context, state, isInitialized) => isInitialized ? const ProfilePage() : const ProfileSkeleton(), ) ``` Without a binding, `isInitialized` is always `true`. Provide `builder` **or** `initBuilder`, not both. ## Cross-fade animation With `initTransitionDuration`, an `AnimatedSwitcher` cross-fades from the loading state to the content. `Duration.zero` or `null` disables it. It applies to `builder` (with or without a shell). ```dart PlayxPageConfig(initTransitionDuration: Duration(milliseconds: 250)) ``` ## Changing the global config Provide a new `PlayxPageConfig` to `PlayxNavigationBuilder` and pages that depend on it update (for example to change the loading widget when the theme changes). --- # Guards and redirects Redirects run **before** a page is built, so a guarded page never flashes and its `onEnter` / `onExit` never run when navigation is redirected. Playx Navigation offers three levels, evaluated in this order for the destination route: 1. `guards` on the route (`PlayxGuard`), in order. 2. The route's binding `redirect`. 3. The route's own `redirect` (go_router's). The first one that returns a location wins; `null` means "continue". ## `PlayxGuard` ```dart class AuthGuard extends PlayxGuard { const AuthGuard(); @override FutureOr redirect(BuildContext context, GoRouterState state) { return AuthService.isLoggedIn ? null : '/login?from=${state.matchedLocation}'; } } PlayxRoute( path: '/account', guards: const [AuthGuard()], builder: (context, state) => const AccountPage(), ) ``` - Guards may be async (`Future`). The chain stays synchronous as long as every guard answers synchronously, so navigation is not delayed by a frame. - Guards on a route also protect its child routes. - Create one inline with `PlayxGuard.from((context, state) => ...)`. ```dart guards: [ PlayxGuard.from((context, state) => user.isAdmin ? null : '/forbidden'), const AuthGuard(), ], ``` ## Binding `redirect` Validate parameters before building the page: ```dart class JobDetailsBinding extends PlayxBinding { @override FutureOr redirect(BuildContext context, GoRouterState state) => state.intPathParam('id') == null ? '/jobs' : null; } ``` It runs only when the binding's own route is the destination, not for its child routes (use a guard for that). Prefer it over navigating away from `onEnter`: the page is never built with missing data and `onEnter` / `onExit` don't run. ## Route `redirect` go_router's own `redirect` still works, and runs last. It composes with guards and bindings. ## Global redirects Use go_router's top-level `GoRouter(redirect: ...)` for app-wide rules. It runs before route-level redirects. ## Parameter helpers `GoRouterState` gets safe accessors so redirects and builders never throw on bad input: | Helper | Returns | |---|---| | `state.extraAs()` | `extra` if it is a `T`, otherwise `null`. | | `state.intPathParam('id')` | the path parameter as `int?`. | | `state.intQueryParam('page')` | the query parameter as `int?`. | > **`extra` is not part of the URL:** After a web refresh, a typed or shared URL, or a deep link, `state.extra` is `null`. Treat > it as an optional shortcut and load data by id. See [Web](web.md). --- # Error handling Page setup can be slow or fail: a binding's `onEnter` throws, a request hangs, a controller's constructor fails, or `onInitApp` fails at boot. Playx Navigation turns these into a visible, retryable state instead of a spinner that never ends. ## `errorBuilder` and `enterTimeout` ```dart PlayxRoute( path: '/products', binding: ProductsBinding(), enterTimeout: const Duration(seconds: 10), errorBuilder: (context, state, error, stackTrace, retry) => ErrorView( message: '$error', onRetry: retry, ), builder: (context, state) => const ProductsPage(), ) ``` | Parameter | Meaning | |---|---| | `error` | What was thrown. A `TimeoutException` when `enterTimeout` elapsed. | | `stackTrace` | Its stack trace. | | `retry` | Runs the setup again: a fresh `onEnter` and, for route controllers, a fresh controller. | Set both globally with `PlayxPageConfig(errorBuilder: ..., enterTimeout: ...)`; a route's values override the global ones. ## What counts as a failure - `onEnter` throws, or exceeds `enterTimeout`. - A [route controller](controllers-and-views.md) factory throws, or `PlayxPageLifecycle.onPageEnter` throws. - `onInitApp` of any binding fails at boot: pages wait for boot, so they fail too. A failed page is not entered: no `onHidden` / `onReEnter` / `onExit` runs for it, and its `PlayxPageState` is `pending`. After `retry` it behaves like a normal page. ## Without an `errorBuilder` The error is reported with `FlutterError.reportError` (so it reaches your crash reporting and shows in debug logs) and the page keeps its loading state. It is never left as an unhandled async error. ## Errors in other lifecycle callbacks An exception in `onHidden`, `onReEnter` or `onExit` is reported with `FlutterError.reportError`. The page's callback queue continues, so a failing `onHidden` does not stop later callbacks, and `onExit` still disposes the page's scope and controller. Errors while unregistering or disposing a route controller are reported, and every cleanup step still runs. ## Boot failures `PlayxNavigation.boot` rethrows `onInitApp` errors to its caller. `PlayxNavigationBuilder` reports them with `FlutterError.reportError` instead. `PlayxNavigation.isInitialized` stays `false`, and `await PlayxNavigation.ensureInitialized` throws the same error. --- # Scopes Every page with a binding or controller gets a `PlayxScope`: one per **page visit**, from `onEnter` to `onExit`. It solves the classic problem of stacked pages (`details/1` over `details/2`, or `edit` over `create` sharing a `JobFormController`) overwriting or deleting each other's controllers. It works with any state management (GetX, Bloc, Provider, ChangeNotifier, plain classes). ## Getting the scope ```dart final scope = PlayxScope.of(context); // throws a StateError if there is none final maybe = PlayxScope.maybeOf(context); // null outside a page with a binding or controller ``` `context` can be the context passed to a binding callback, or any context inside the page's widget tree. In binding callbacks the same scope is returned in `onEnter`, `onHidden`, `onReEnter` and `onExit`. The scope is disposed right after `onExit` completes. ## API | Member | Purpose | |---|---| | `id` | A unique, never reused id for this page visit. Use it as a GetX `tag`, a family key, ... | | `put(value, {dispose})` | Store an object in the page. `dispose(value)` runs when the scope ends. | | `get()` / `maybeGet()` / `has()` | Read it. Exact type first, then the first stored value that `is T`. | | `onDispose(callback)` | Run cleanup after `onExit` completes (reverse registration order). | | `state` | This page's `GoRouterState`. | | `binding` | The binding the scope belongs to. | | `pageState`, `isActive`, `isDisposed` | This page's lifecycle state. | `binding.currentState` is shared by every page using the binding; `scope.pageState` belongs to one page. Storing again under the same type replaces the value for lookups; the earlier value's `dispose` still runs when the scope ends. Calling `put` or `onDispose` after the scope is disposed throws a `StateError`. Errors thrown by disposers are reported and the remaining disposers still run. ## Patterns ### Lifecycle methods with the scope id as a tag (GetX) ```dart class JobDetailsBinding extends PlayxBinding { @override Future onEnter(BuildContext context, GoRouterState state) async { Get.put( JobDetailsController(id: state.intPathParam('id')!, job: state.extraAs()), tag: PlayxScope.of(context).id, ); } @override Future onHidden(BuildContext context) async => Get.find(tag: PlayxScope.of(context).id).pauseUpdates(); @override Future onReEnter(BuildContext context, GoRouterState? state, bool popped) async => Get.find(tag: PlayxScope.of(context).id).resumeUpdates(); @override Future onExit(BuildContext context) async => Get.delete(tag: PlayxScope.of(context).id); } // In the page: final controller = Get.find(tag: PlayxScope.of(context).id); ``` ### Cleanup registered in `onEnter` `onExit` is optional, so cleanup can be attached where the controller is created: ```dart @override Future onEnter(BuildContext context, GoRouterState state) async { final scope = PlayxScope.of(context); Get.put(JobDetailsController(), tag: scope.id); scope.onDispose(() => Get.delete(tag: scope.id)); } ``` ### Keep the controller in the scope (no global registry) ```dart @override Future onEnter(BuildContext context, GoRouterState state) async { PlayxScope.of(context).put( JobDetailsController(id: state.intPathParam('id')!), dispose: (controller) => controller.onClose(), ); } // In the page, in onHidden / onReEnter / onExit, or in widgets: final controller = PlayxScope.of(context).get(); // or: context.controller() ``` See [Route controllers and views](controllers-and-views.md) for the declarative version of this. ## Shared (unscoped) resources `binding.activeScopes` lists the pages currently using the binding. A page leaves the list **before** its `onExit` runs, so this only cleans up when no other page needs the resource: ```dart @override Future onExit(BuildContext context) async { if (activeScopes.isEmpty) Get.delete(); } ``` ## Dialogs and bottom sheets Dialogs and sheets are shown above the page's widget tree. Pass the scope down with `PlayxScopeProvider`: ```dart final scope = PlayxScope.of(context); showModalBottomSheet( context: context, builder: (_) => PlayxScopeProvider(scope: scope, child: const JobFilterSheet()), ); ``` --- # Route controllers and views The simplest way to give a page state: declare the controller type on the route. The package creates one controller **per page visit**, runs its lifecycle hooks, and disposes it. Views read it like GetX's `GetView`. No binding class is needed (but a binding can be added too). ## Declaring a controller ```dart PlayxRoute( path: ':id', controller: (context, state) => JobDetailsController( jobId: state.intPathParam('id')!, job: state.extraAs(), // null on web refresh / deep link ), disposeController: (controller) => controller.onClose(), // optional builder: (context, state) => const JobDetailsView(), ) ``` `PlayxShellBranch` accepts the same `controller` / `disposeController` parameters. - The factory runs when the page is entered, after every `onInitApp` finished. The controller is stored in the page's [scope](scopes.md) under `T` and exists before the first build. - `disposeController` runs when the page exits (after `onPageExit`). - Two stacked pages of the same route each get their own controller. ## Controller lifecycle hooks Mix in `PlayxPageLifecycle` to react to the page's lifecycle from the controller itself. The `onPage*` names do not clash with `GetxController`'s `onInit` / `onReady` / `onClose`. ```dart class JobsController extends GetxController with PlayxPageLifecycle { @override Future onPageEnter(GoRouterState state) async => loadFirstPage(); @override void onPageHidden() => tourController.dismissTour(); @override void onPageReEnter(GoRouterState? state, bool wasPoppedAndReentered) { if (pagingController.itemList?.isNotEmpty ?? false) { tourController.startTour(checkRoute: false); } } @override void onPageExit() => saveScrollPosition(); } ``` All hooks may be sync or async. While `onPageEnter` runs, the page shows its loading state ([Page configuration](page-configuration.md)), so the view only builds once the data is loaded (unless the route uses `waitForBinding: false`). ### Order For a route with both a binding and a controller: ``` enter: create controller -> registerController -> binding.onEnter -> onPageEnter -> content builds hidden: binding.onHidden -> onPageHidden reEnter: binding.onReEnter -> onPageReEnter exit: binding.onExit -> onPageExit -> unregisterController -> disposeController ``` - The controller is created **before** `binding.onEnter`, so the binding can call `PlayxScope.of(context).get()`. - Callbacks never overlap, and exit waits for a running enter. - Replace or a path-parameter change disposes the old controller before the new one is created. - A page behind a deep link gets its controller when it is first shown. Until then it shows its loading widget, even with `waitForBinding: false`. - If the factory or `onPageEnter` throws, the route's [`errorBuilder`](error-handling.md) is shown. `retry` creates a fresh controller. ## `PlayxView` `PlayxView` gets the page's controller and passes it to `buildView`: ```dart class JobsView extends PlayxView { const JobsView({super.key}); @override Widget buildView(BuildContext context, JobsController controller) { return Scaffold( body: const BuildJobsList(), // a child view in another file floatingActionButton: FloatingActionButton(onPressed: controller.refresh), ); } } ``` Child widgets in separate files work the same way. Any widget below the page resolves **the same page's** controller: ```dart class BuildJobsList extends PlayxView { const BuildJobsList({super.key}); @override Widget buildView(BuildContext context, JobsController controller) => ListView(children: [for (final job in controller.jobs) BuildJobItem(job: job)]); } class BuildJobItem extends PlayxView { const BuildJobItem({super.key, required this.job}); final Job job; @override Widget buildView(BuildContext context, JobsController controller) => ListTile( title: Text(job.title), trailing: IconButton( icon: const Icon(Icons.delete), onPressed: () => controller.delete(job), // closures are safe ), ); } ``` Plain widgets can use the context extension: ```dart final controller = context.controller(); // throws a clear StateError if missing final maybe = context.maybeController(); // null if missing ``` - `const` constructors and callbacks are safe: the controller is resolved from the context on every build and passed in. A widget instance never stores it. - A view can ask for a **base type**: `PlayxView` works on both `PlayxRoute` and `PlayxRoute`. - In a `shellBuilder` or `initBuilder` the controller may not exist yet; use `maybeController()`. - Dialogs and bottom sheets need [`PlayxScopeProvider`](scopes.md#dialogs-and-bottom-sheets). ### Lookup order 1. The page's scope: a route controller, or a value a binding stored with `PlayxScope.of(context).put`, including values of a subtype. 2. `PlayxPageConfig.findController`: lets `PlayxView` find controllers a binding registered in an external registry. See [GetX and other registries](state-management-interop.md). So `PlayxView` also works with plain bindings: ```dart class JobsBinding extends PlayxBinding { @override Future onEnter(BuildContext context, GoRouterState state) async { PlayxScope.of(context).put(JobsController(), dispose: (c) => c.onClose()); } } ``` ## Migrating from `GetView` | Before (GetX) | After | |---|---| | `class X extends GetView` | `class X extends PlayxView` | | `Widget build(BuildContext context)` | `Widget buildView(BuildContext context, T controller)` | | body uses `controller` | unchanged | | `Get.find()` in a widget | `context.controller()` | | binding `Get.put` / `Get.delete` | `PlayxRoute(controller:, disposeController:)`, or keep the binding | | binding `onHidden` / `onReEnter` using `Get.find` | `PlayxPageLifecycle` hooks on the controller, or keep them in the binding | --- # GetX and other registries The package has no dependency on GetX or any state management library. If your app uses a global registry (GetX, `get_it`, ...) you can mirror route controllers into it and let `PlayxView` find controllers that bindings registered there. Configure it once, app-wide, with three optional callbacks on `PlayxPageConfig`. ```dart PlayxNavigationBuilder( router: router, config: PlayxPageConfig( // A route controller was created: register it. registerController: (T controller, PlayxScope scope) => Get.put(controller, tag: scope.id), // A route controller is about to be disposed: unregister it. unregisterController: (T controller, PlayxScope scope) => Get.delete(tag: scope.id), // PlayxView / context.controller() found nothing in the page scope: look in the registry. findController: (PlayxScope scope) => Get.isRegistered(tag: scope.id) ? Get.find(tag: scope.id) : null, ), builder: (context) => const MyApp(), ) ``` | Callback | Called | Receives | |---|---|---| | `registerController` | Right after a `PlayxRoute(controller: ...)` controller is created. | The controller as its route type `T`, and its page's `scope`. | | `unregisterController` | Right before it is disposed (before `disposeController`). | Same. | | `findController` | When `PlayxView` / `context.controller()` finds no `T` in the page scope. | The page's `scope`. Return `null` if there is none. | The type parameter is the route's declared `T` (for `PlayxRoute` it is `EditJobController`), so registrations are typed. ## Tagged vs untagged - **Tagged with `scope.id`** keeps stacked pages of the same type apart (`details/1` and `details/2` each have their controller). Look controllers up with `Get.find(tag: PlayxScope.of(context).id)` or, simpler, `context.controller()`. - **Untagged** (`Get.put(controller)` / `Get.find()`) lets any code, for example another controller, find the controller without a tag. Stacked pages of the same type then share one registration, and with GetX `Get.put` keeps the first instance, so use it for pages that exist once. ## Without a registry Skip the config entirely. Controllers live in the page's scope and are reached with `PlayxView` and `context.controller()`. From a binding callback use `PlayxScope.of(context).get()`. ## Other state management The same idea applies to anything that needs a per-page instance, for example Riverpod overrides, Provider, or Bloc: ```dart // Provider: expose the route controller to the subtree. class JobDetailsView extends PlayxView { const JobDetailsView({super.key}); @override Widget buildView(BuildContext context, JobDetailsController controller) => ChangeNotifierProvider.value(value: controller, child: const JobDetailsBody()); } ``` For Bloc, create the bloc in the route's `controller:` factory, close it in `disposeController`, and use `BlocProvider.value` in the view. --- # PlayxNavigation API `PlayxNavigation` is a static facade over the router, so you can navigate from controllers, services and bindings without a `BuildContext`. Boot it first (`PlayxNavigationBuilder(router: ...)` or `PlayxNavigation.boot`). Using it before that throws an exception that explains how to set it up. ## Going forward Names matter here: methods without `Named` take a **location** (`'/jobs/5?tab=open'`), methods with `Named` take a **route name** plus parameters. | Method | go_router call | Stack effect | |---|---|---| | `to(location, {extra})` | `push` | Adds a page on top. Returns a `Future` with the page's result. | | `toNamed(name, {pathParameters, queryParameters, extra})` | `pushNamed` | Same, by name. | | `offAll(location, {extra})` | `go` | Replaces the whole stack with the location's own stack. | | `offAllNamed(name, ...)` | `goNamed` | Same, by name. | | `offAndTo(location, {extra})` | `replace` | Replaces the **top** page only. Pages below stay and are not re-entered. | | `offAndToNamed(name, ...)` | `replaceNamed` | Same, by name. | ```dart // Push and wait for a result: final saved = await PlayxNavigation.toNamed('editJob', pathParameters: {'id': '5'}, extra: job); // Clear the stack: PlayxNavigation.offAllNamed('home'); // Replace the current page (e.g. login -> home): PlayxNavigation.offAndToNamed('home'); ``` > **`offAndTo` returns the *new* page's result:** Like `to`, the future returned by `offAndTo` / `offAndToNamed` completes when the new page is > popped (with its result), **not** when the replacement happens. Don't `await` it if you > only want to wait for the navigation: > > ```dart > PlayxNavigation.offAndTo('/home'); // fire and forget > final ok = await PlayxNavigation.offAndTo('/edit'); // wait for the result > ``` `offAll` / `offAllNamed` return a `Future` that completes immediately. The lifecycle that results from each is described in [Bindings and lifecycle](bindings.md). ## Going back | Method | Behavior | |---|---| | `pop([result])` | Pops the top page. Throws if there is nothing to pop. | | `maybePop([result])` | Pops if possible; returns whether it did. | | `canPop()` | Whether something can be popped. | | `back([result])` | Pops, or goes to the page's parent when there is nothing to pop. Returns `false` if neither is possible. | | `canGoBack` / `parentLocation` | Whether `back()` can do something, and where it would go. | | `popOrGo(location, {result, extra})` | Pops, or goes to a specific fallback location. | | `popOrGoNamed(name, ...)` | Same, by name. | | `popUntil(location, {orGo})` | Pops until the page showing `location` is on top. | | `popUntilNamed(name, {pathParameters, orGo})` | Same, by name. | `popUntil` compares paths only (query and fragment are ignored) and the page closest to the top wins. It returns `true` when that page is on top. If the location is not in the stack, nothing is popped and it returns `false`, unless `orGo: true`, which then goes to the location. Pages above the target receive `onHidden` / `onExit` and the target `onReEnter(popped: true)`. See [Web](web.md) for `back()`, `parentLocation` and `popUntil` when the stack may be empty. ## Tabs ```dart PlayxNavigation.goToBranch(index: 1, navigationShell: shell); ``` Restores the branch's last location. Pass `initialLocation: true` to reset it (by default `true` when tapping the already-selected branch). ## State and listeners | Member | Description | |---|---| | `currentState` | Current `GoRouterState`, or `null` while go_router shows its error page. | | `currentRoute` / `currentRouteName` | The top `GoRoute` and its name. | | `namedLocation(name, {pathParameters, queryParameters})` | Builds a location string. | | `addRouteChangeListener(l)` / `removeRouteChangeListener(l)` | Notified on every route change. | | `refresh()` | Re-evaluates redirects for the current location. Doesn't rebuild pages or change lifecycle. | | `restore(matchList)` | Restores a saved `RouteMatchList`. | | `goRouter` | The underlying `GoRouter`. | | `playxRouter` | The `PlayxRouter` with helpers like `parentOf`, `stateFor`, `pageStack`, `popToPage`. | | `rootNavigatorKey`, `navigationContext` | The root navigator's key and its current context (for dialogs, snack bars). | | `hasRouter` | Whether a router has been set up. | ## Boot and bindings | Member | Description | |---|---| | `boot({required router})` | Finds every binding, runs `onInitApp`, sets `isInitialized`. Calling it again re-boots with the new router. | | `ensureInitialized` | A `Future` that completes when boot finished. May be awaited before `boot` is called. If boot failed it completes with that error. | | `isInitialized` | `true` after a successful boot, `false` after a failed one. | | `bindings`, `findBinding()`, `findBindingOrNull()` | The binding registry. | | `setupWeb({usePathUrlStrategy, optionURLReflectsImperativeAPIs})` | Path URLs and push-reflecting URLs on web. No-op elsewhere. | ## Breadcrumbs and titles | Member | Description | |---|---| | `breadcrumbs(context, {mode, rootLocation})` | The breadcrumb trail of the current page. | | `setBreadcrumbLabel(context, label)` | Set (or with `null` clear) the current page's runtime label. | | `breadcrumbsListenable` | Notifies when the trail may have changed. | | `pageTitle` | The browser tab title last applied by `PlayxNavigationBuilder.pageTitle`. | See [Breadcrumbs and page titles](breadcrumbs.md). ## `PlayxRouter` The instance behind the facade is available as `PlayxNavigation.playxRouter`. It exposes the same navigation methods plus lower-level helpers that are useful for custom navigation UI: | Member | Description | |---|---| | `parentOf(state)` | The location `back()` would go to from the page described by `state`. | | `stateFor(location)` | The `GoRouterState` a location would show, without navigating. `null` if no route matches. | | `isShellBranchRoot(location)` | Whether the location is the first page of its shell branch. | | `pageStack` | The states of the pages in the stack, bottom to top. | | `popToPage(pageKey)` | Pops until the page with that key is on top. | | `stateOrNull` | Like `state`, but `null` instead of throwing when nothing matched. | --- # Web Web apps differ from mobile in ways that affect navigation: pages can be opened directly by URL, the user can refresh at any time, and the browser has its own back and forward buttons. Playx Navigation has features for each. ## Setup Call this before `runApp` for path URLs (no `#`) and so that `push` is reflected in the browser URL: ```dart void main() { PlayxNavigation.setupWeb(); // usePathUrlStrategy: true, optionURLReflectsImperativeAPIs: true runApp(const MyApp()); } ``` It does nothing outside the web. ## `extra` does not survive a refresh `state.extra` is not part of the URL. After a refresh, a typed or shared URL, or a deep link, it is `null`. Treat it as an optional shortcut and load by id when it is missing. ```dart class JobDetailsController with PlayxPageLifecycle { JobDetailsController({required this.id, Job? job}) : job = Rxn(job); final int id; final Rxn job; @override Future onPageEnter(GoRouterState state) async { job.value ??= await repository.getJob(id); } } controller: (context, state) => JobDetailsController( id: state.intPathParam('id')!, job: state.extraAs(), // typed, never throws, null when missing ), ``` `state.extraAs()`, `state.intPathParam(name)` and `state.intQueryParam(name)` never throw. To keep `extra` across browser back and forward, give `GoRouter` an `extraCodec`. Validate ids before the page is built with a binding's [`redirect`](guards-and-redirects.md) so a bad URL never builds a half-empty page. ## Back to the parent After a refresh or deep link there may be nothing to pop, so Flutter's automatic `AppBar` back button is missing. `PlayxNavigation.back()` pops when it can and otherwise goes to the page's **parent**: from a job's details to the jobs list, even when the details page was opened directly. The parent is found in this order: 1. The route's `parentLocation`, if it returns a value. 2. The nearest shorter path that matches a route: `/jobs/5/edit` -> `/jobs/5` -> `/jobs`. The automatic parent never falls back to `/`, so tab roots such as `/jobs` have no parent unless you set one. ```dart // Nested or path-shaped routes need nothing extra: PlayxRoute(path: '/jobs', builder: ..., routes: [ PlayxRoute(path: ':id', builder: ...), // /jobs/5 -> back -> /jobs ]), // When the path doesn't contain the parent, say where to go: PlayxRoute( path: '/job/:id', parentLocation: (state) => '/jobs', builder: ..., ), PlayxRoute( path: '/edit-job/:id', parentLocation: (state) => '/jobs/${state.pathParameters['id']}', builder: ..., ), ``` ### `PlayxBackButton` ```dart AppBar( leading: PlayxNavigation.canGoBack ? const PlayxBackButton() : null, title: const Text('Job details'), ) ``` `PlayxBackButton` calls `back()`. It renders nothing when `canGoBack` is `false`, and accepts `onPressed` (called first, e.g. to save a draft) and `color`. | API | Purpose | |---|---| | `PlayxNavigation.back()` | Pop, or go to the parent. Returns `false` if neither is possible. | | `PlayxNavigation.canGoBack` | Whether `back()` can do something. | | `PlayxNavigation.parentLocation` | The location `back()` goes to when there is nothing to pop. | | `PlayxNavigation.popOrGo(location)` | Pop, or go to a specific fallback. | | `PlayxNavigation.popUntil(location, orGo: true)` | Pop back to a page, or go there if it isn't in the stack. | ## `popUntil` Return to a page deeper in history, for example back to the jobs list after a create flow: ```dart PlayxNavigation.popUntil('/jobs'); // false if '/jobs' isn't in the stack PlayxNavigation.popUntil('/jobs', orGo: true); // goes to '/jobs' if it isn't PlayxNavigation.popUntilNamed('jobs', orGo: true); ``` Pages above the target receive `onHidden` / `onExit` and the target receives `onReEnter`. Details in the [navigation API](navigation-api.md#going-back). ## Browser back and forward The browser's buttons behave like `pop` and `push`: the page that was left gets `onExit`, the page revealed gets `onReEnter`, and going forward creates a new page with `onEnter`. ## Refresh A refresh restarts the app: `onInitApp` runs again, and the pages for the URL behave like a deep link. Only the visible page enters; pages behind it are *pending* until they are shown. Controllers and `extra` from before the refresh are gone, so rebuild state from the URL. ## Browser tab titles `PlayxNavigationBuilder(pageTitle: PlayxPageTitle(...))` keeps the tab title in sync with the current page, using the labels you declared for breadcrumbs. See [Breadcrumbs and page titles](breadcrumbs.md#browser-tab-titles). ## Breadcrumbs Breadcrumbs are derived from the route tree, so they are correct after a refresh or a deep link. See [Breadcrumbs and page titles](breadcrumbs.md). --- # Breadcrumbs and page titles Breadcrumbs are derived from navigation. Give routes a label, place a `PlayxBreadcrumbs` widget, and every page gets a correct, tappable trail, also after a web refresh or deep link. ```dart PlayxShellBranch( path: '/jobs', breadcrumb: (context, state) => context.l10n.jobs, // localized labels work builder: (context, state) => const JobsView(), routes: [ PlayxRoute( path: ':id', breadcrumb: (context, state) => 'Job #${state.pathParameters['id']}', builder: (context, state) => const JobDetailsView(), routes: [ PlayxRoute( path: 'edit', breadcrumb: (context, state) => context.l10n.edit, builder: (context, state) => const EditJobView(), ), ], ), ], ) // In the shell layout or any page (rebuilds on every navigation): const PlayxBreadcrumbs(mode: PlayxBreadcrumbMode.shellBranch) // Jobs > Job #5 > Edit ``` ## Modes | Mode | Trail | Tapping a crumb | |---|---|---| | `hierarchy` (default) | The current page and its parents, using the same parent rule as `back()`: `parentLocation`, otherwise the nearest shorter matching path. `rootLocation: '/home'` prepends a root: `Home > Jobs > Job #5 > Edit`. | Goes to it. | | `shellBranch` | Like `hierarchy`, but starting at the current shell branch's root: `Jobs > Job #5 > Edit`. Outside a shell it is the same as `hierarchy`. | Goes to it. | | `history` | The pages actually in the stack, bottom to top. Depends on how the user navigated and resets on refresh. | Pops back to it. | - Pages without a label are left out, but the trail still continues to their parents. - The last item is the current page and is not tappable. - `rootLocation` is only used by `hierarchy`, and is not duplicated if already part of the trail. ## Labels A crumb's label comes from the first of these that provides one: 1. **A runtime label** set by a live page, for loaded data: ```dart Obx(() => PlayxBreadcrumbLabel(label: controller.job.value?.title)) // or from a binding callback / any widget in the page: PlayxNavigation.setBreadcrumbLabel(context, job.title); ``` The label stays while the page is in the stack, so a child page shows `Jobs > Plumbing repair > Edit`. It is removed when the page goes away. A `null` label falls back to the route's label. It also works inside plain `GoRoute` pages. 2. **The route's** `breadcrumb: (context, state) => ...`. 3. **The binding's** `breadcrumb` override, which keeps route definitions short: ```dart class JobDetailsBinding extends PlayxBinding { @override String? breadcrumb(BuildContext context, GoRouterState state) => 'Job #${state.pathParameters['id']}'; } ``` `context` is the context of the widget showing the breadcrumbs, so `context.l10n` works even in a shell header placed above the pages. ## The widget ```dart PlayxBreadcrumbs( mode: PlayxBreadcrumbMode.hierarchy, rootLocation: '/home', maxItems: 4, // Home > ... > last 3; the "..." opens a menu with the hidden items hideIfSingle: true, separator: const Icon(Icons.chevron_right, size: 16), itemBuilder: (context, item) => CustomText( item.label, color: item.isCurrent ? context.colors.onSurface : context.colors.subtitleTextColor, ), ) ``` | Parameter | Default | Meaning | |---|---|---| | `mode`, `rootLocation` | `hierarchy`, none | Which trail. | | `maxItems` | `4` | More items collapse to first, `...`, last `maxItems - 1`. `null` never collapses. | | `collapsedMenu` | `true` | Tapping `...` opens a menu with the hidden items. | | `hideIfSingle` | `false` | Render nothing for a trail of one item or less. | | `separator`, `spacing` | chevron icon, `8` | Between items. | | `style`, `currentStyle` | theme `bodyMedium` | Text styles (tappable and current). | | `itemBuilder` | `Text` | Your own item content. Taps are handled for you. | | `ellipsisBuilder` | `...` text | Your own collapsed content. | The widget scrolls horizontally when it doesn't fit, provides its own transparent `Material` (so it works in a header above the router's `Navigator`), and rebuilds on navigation and label changes. ### Keep your own widget `PlayxBreadcrumbsBuilder` gives you the items and rebuilds when they change: ```dart PlayxBreadcrumbsBuilder( mode: PlayxBreadcrumbMode.shellBranch, builder: (context, items) => BreadcrumbHeader( items: [for (final item in items) BreadcrumbItem(title: item.label, onTap: item.navigate)], ), ) ``` Each `PlayxBreadcrumbItem` has `label`, `location`, `state` (path parameters, ...), `isCurrent`, and `navigate()` (goes to it, or pops back to it in `history` mode; does nothing for the current page). For one-off reads use `PlayxNavigation.breadcrumbs(context, mode: ...)`, and listen to `PlayxNavigation.breadcrumbsListenable` to rebuild yourself. ## Browser tab titles The tab title can follow the current page, reusing the same labels. Pass a `PlayxPageTitle` to `PlayxNavigationBuilder`: ```dart PlayxNavigationBuilder( router: router, pageTitle: const PlayxPageTitle(appName: 'Jobs Dashboard'), builder: (context) => MaterialApp.router( routerConfig: router, // Keeps the page title if MaterialApp rebuilds (see below). onGenerateTitle: (context) => PlayxNavigation.pageTitle ?? 'Jobs Dashboard', ), ) // /jobs/5 once the job has loaded: "Plumbing repair · Jobs · Jobs Dashboard" ``` | Parameter | Default | Meaning | |---|---|---| | `appName` | none | Appended after the page labels. Used alone when the page has no label. | | `separator` | `' · '` | Between parts. | | `maxItems` | `2` | How many labels to include, current page first, then its parents. `null` includes all. | | `mode`, `rootLocation` | `hierarchy`, none | Which trail the title is built from. | | `builder` | none | Build the whole title yourself from the trail. Return `null` to leave the title unchanged. | The title updates after every navigation and whenever a label changes (for example when the job's name loads). It is applied with `SystemChrome.setApplicationSwitcherDescription`, which sets the document title on web (and the task label on Android). > **MaterialApp resets the title when it rebuilds:** Flutter's `MaterialApp` sets the tab title to its own `title` each time it rebuilds (theme or > locale changes, a rebuilt parent). Return `PlayxNavigation.pageTitle` from `onGenerateTitle`, as > shown above, so a rebuild keeps the current page title. --- # Testing your app Bindings, controllers and guards are easy to test with Flutter's widget tests: build a small router, pump it inside `PlayxNavigationBuilder`, navigate, and assert on what happened. This package's own test suite uses exactly this approach. ## Test setup ```dart Future pumpApp(WidgetTester tester, GoRouter router) async { await tester.pumpWidget(PlayxNavigationBuilder( router: router, builder: (_) => MaterialApp.router(routerConfig: router), )); await tester.pumpAndSettle(); return router; } ``` - Each test should build its own `GoRouter` and pump it. `PlayxNavigation` is static; the builder boots the new router (and re-runs `onInitApp`) for you. - Use `unawaited(router.push('/path'))` followed by `pumpAndSettle()` to navigate. - Test files run in separate isolates, so static state does not leak between files. ## Test the lifecycle of a binding Record events in a list and assert on their order: ```dart class RecordingBinding extends PlayxBinding { RecordingBinding(this.name, this.log); final String name; final List log; @override Future onEnter(BuildContext c, GoRouterState s) async => log.add('$name:enter'); @override Future onHidden(BuildContext c) async => log.add('$name:hidden'); @override Future onReEnter(BuildContext c, GoRouterState? s, bool popped) async => log.add('$name:reEnter${popped ? '(popped)' : ''}'); @override Future onExit(BuildContext c) async => log.add('$name:exit'); } testWidgets('details: push and pop', (tester) async { final log = []; final router = GoRouter(initialLocation: '/jobs', routes: [ PlayxRoute( path: '/jobs', binding: RecordingBinding('jobs', log), builder: (_, __) => const Text('jobs'), routes: [ PlayxRoute( path: ':id', binding: RecordingBinding('details', log), builder: (_, __) => const Text('details'), ), ], ), ]); await pumpApp(tester, router); log.clear(); unawaited(router.push('/jobs/5')); await tester.pumpAndSettle(); expect(log, ['jobs:hidden', 'details:enter']); router.pop(); await tester.pumpAndSettle(); expect(log, [ 'jobs:hidden', 'details:enter', 'details:hidden', 'jobs:reEnter(popped)', 'details:exit', ]); }); ``` To test **your own** bindings, build a router with your real binding and routes and assert on the effects (registered controllers, repository calls) instead of a log. ## Test controllers A route controller is a plain Dart class. Unit-test it directly; `PlayxPageLifecycle` hooks are ordinary methods: ```dart test('loads the job by id when extra is missing', () async { final controller = JobDetailsController(id: 5, job: null); await controller.onPageEnter(fakeState); // any GoRouterState expect(controller.job.value?.id, 5); }); ``` To test the **wiring** (that the page creates, shows and disposes the controller), pump a router with the real `PlayxRoute` and a fake `controller:` factory: ```dart testWidgets('disposes the controller on exit', (tester) async { var disposed = false; final router = GoRouter(routes: [ PlayxRoute( path: '/', controller: (_, __) => FakeJobsController(), disposeController: (_) => disposed = true, builder: (_, __) => const JobsView(), ), PlayxRoute(path: '/other', builder: (_, __) => const Text('other')), ]); await pumpApp(tester, router); router.go('/other'); await tester.pumpAndSettle(); expect(disposed, isTrue); }); ``` `PlayxView` needs a page scope, so test views through a router like this (a scope can only be created by a page). ## Test guards and redirects ```dart testWidgets('redirects to login when logged out', (tester) async { final router = GoRouter(routes: [ PlayxRoute(path: '/', builder: (_, __) => const Text('home')), PlayxRoute(path: '/login', builder: (_, __) => const Text('login')), PlayxRoute( path: '/account', guards: [PlayxGuard.from((_, __) => loggedIn ? null : '/login')], builder: (_, __) => const Text('account'), ), ]); await pumpApp(tester, router); router.go('/account'); await tester.pumpAndSettle(); expect(find.text('login'), findsOneWidget); }); ``` ## Test navigation from code Anything that calls `PlayxNavigation.*` can be tested the same way: pump a router, call your code, assert `PlayxNavigation.currentState?.matchedLocation` or find widgets. ```dart expect(PlayxNavigation.currentState?.matchedLocation, '/jobs/5'); ``` ## Test breadcrumbs and page titles Breadcrumbs only need a router and a context inside the app (use `MaterialApp.router`'s `builder` to capture one). For page titles, mock the platform channel and collect the labels: ```dart final titles = []; tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( SystemChannels.platform, (call) async { if (call.method == 'SystemChrome.setApplicationSwitcherDescription') { final label = (call.arguments as Map)['label'] as String; if (label.isNotEmpty) titles.add(label); // MaterialApp sends an empty one } return null; }, ); ``` ## Tips - Use `--no-pub` (`flutter test --no-pub`) in CI after `flutter pub get` to skip a second resolve. - Prefer `pumpAndSettle()` after navigation: lifecycle callbacks and transitions are asynchronous. - Assertions about `onExit` must wait for the pop animation to finish. - Run with `flutter test --coverage` to measure coverage. This package's suite covers 99% of its lines. --- # Migrating to 3.0 3.0.0 reworks how the binding lifecycle is tracked (per page instead of per route) and adds page scopes, route controllers, web helpers, breadcrumbs and page titles. Most apps only need to check the items under [What changes](#what-changes). Everything from 2.x still compiles, apart from the small signature changes listed below. ```yaml dependencies: playx_navigation: ^3.0.0 ``` > **About 2.2.0:** 2.2.0 was developed on the way to 3.0.0 and was never published; its changes are part of 3.0.0. ## What changes ### Lifecycle behavior The lifecycle now belongs to each page instance. This fixes real bugs (see the [changelog](https://github.com/playx-flutter/playx_navigation/blob/main/CHANGELOG.md)) and changes observable behavior in a few places. Check bindings that depend on any of these: | Before | Now | |---|---| | The first navigation away from the initial route did not call `onHidden` / `onReEnter` for it. | It does. | | `router.replace` (`offAndTo`) reused the old page's state: the new binding never ran `onEnter` and the old one never ran `onExit`. | The old page exits, then the new one enters. | | Going from `/item/1` to `/item/2` did not re-run `onEnter` with the new parameters. | The old page exits and a new one enters with the new parameters. | | `onReEnter` was used to refresh a page's parameters (`updateJob(...)`). | A different path parameter is a new page (`onExit`, then `onEnter`), so that workaround is no longer needed. | | The same route stacked twice, or a binding shared by several routes, mixed up lifecycle state. | Every page has its own lifecycle. | | Leaving a page while `onEnter` was still running skipped `onExit`. | `onExit` runs after `onEnter` finishes. | | `onEnter` could start before an async `onInitApp` finished. | `onEnter` waits for boot. | | `onExit` ran synchronously when the widget was disposed. | It is queued behind running callbacks, so it can run slightly later. | | On pop, order between the revealed page's `onReEnter` and the popped page's `onExit` was unspecified. | `onReEnter` first (immediately), `onExit` after the exit animation. | | `wasPoppedAndReentered` compared path prefixes. | It uses the router's page stack. It is also `true` when popping a top-level route back into a tab, or `details/2` back to `details/1`. | | An exception in `onEnter` was an unhandled async error and left the page loading forever. | It is reported with `FlutterError.reportError` (or shown by `errorBuilder`). | If you relied on the old behavior of any of these, review the [lifecycle guarantees](bindings.md#guarantees). ### Signature and type changes | Change | Action | |---|---| | `PlayxRoute` and `PlayxShellBranch` are generic (`PlayxRoute`). | None: `PlayxRoute(...)` infers `Object`. Raw `is PlayxRoute` checks still match. | | `PlayxBinding.onExit` is optional (no-op by default). | None. Existing overrides still work. | | `PlayxNavigation.offAndTo` and `offAndToNamed` return `Future` (they were `Future`). | None for fire-and-forget calls. If you `await` them, note the future completes when the **new page is popped** (with its result), as `to` does. | | `currentState`, `currentRoute` and `currentRouteName` return `null` instead of throwing while go_router shows its error page. | None. | | `PlayxNavigation.isInitialized` is `false` after a failed boot (it used to be `true`). | None. | | `PlayxNavigation.ensureInitialized` can be awaited before `boot` and is released when boot finishes. | None. | | `PlayxNavigationBuilder` boots again when it is given a different router. | None. | | `PlayxPageState` is exported. | None. | ### Guards: composition order Guards run before a binding's `redirect`, which runs before the route's own `redirect`. If you used go_router's `redirect` only, nothing changes. ## What's new You do not need to adopt any of it, but you may want to: - **[Scopes](scopes.md)** (`PlayxScope`): per-page controllers that stacked pages cannot overwrite. - **[Route controllers and `PlayxView`](controllers-and-views.md)**: no binding needed for the common one-controller-per-page case, plus a `GetView` replacement. - **[GetX interop hooks](state-management-interop.md)**: `registerController`, `unregisterController`, `findController`. - **[Guards](guards-and-redirects.md)** and binding `redirect`. - **[Error handling](error-handling.md)**: `errorBuilder`, `enterTimeout`. - **[Web helpers](web.md)**: `back()`, `canGoBack`, `popUntil`, `popOrGo`, `PlayxBackButton`, `extraAs`, `intPathParam`. - **[Breadcrumbs and page titles](breadcrumbs.md)**. ## Migration checklist 1. Update the dependency and run your tests. 2. Search for `await PlayxNavigation.offAndTo` / `offAndToNamed` and check you want to wait for the new page's result. 3. Review bindings that use `onReEnter` to refresh state, `onExit` to delete shared objects, or that are shared between routes (see [sharing a binding](bindings.md#sharing-a-binding-between-live-pages)). 4. Move `Get.put` / `Get.delete` pairs to a [tag per page](scopes.md) if you stack pages of one type. 5. Add `errorBuilder` / `enterTimeout` where a failing `onEnter` would leave users on a spinner. 6. On web, replace hand-written back buttons with `PlayxBackButton` and load data by id when `state.extra` is `null`. --- # Troubleshooting ## "PlayxNavigation is not initialized" You used `PlayxNavigation` before it was booted. Wrap your app in `PlayxNavigationBuilder(router: router, ...)`, or call `await PlayxNavigation.boot(router: router)` before using it. See [Installation and setup](getting-started.md). ## A page shows its loading widget forever `onEnter` never finishes or the page is waiting for boot. - Set `enterTimeout` and an `errorBuilder` to see what happens ([Error handling](error-handling.md)). Without an `errorBuilder`, errors are reported with `FlutterError.reportError`: check your logs. - Pages wait for every `onInitApp`. If one never completes, or boot was never called, no page enters. `await PlayxNavigation.ensureInitialized` completes when boot finished. - Make sure every code path of `onEnter` completes (no un-awaited completer). ## "No X found for this page" (`StateError`) `PlayxView` or `context.controller()` did not find a controller of that type. Either: - declare it: `PlayxRoute(controller: ...)`, - store it from the binding: `PlayxScope.of(context).put(...)`, - or configure `PlayxPageConfig.findController` if it lives in a registry ([GetX and other registries](state-management-interop.md)). Also check the widget is below the page. Dialogs and bottom sheets need [`PlayxScopeProvider`](scopes.md#dialogs-and-bottom-sheets). In a `shellBuilder` or `initBuilder` the controller may not exist yet: use `context.maybeController()`. ## `onExit` runs after `onReEnter` This is intended: when a page is popped, the revealed page re-enters immediately and the popped page exits when its animation ends ([lifecycle guarantees](bindings.md#guarantees)). If two pages share one resource, key it by `PlayxScope.id` or guard cleanup with `activeScopes.isEmpty`. ## A controller was deleted while a page still used it Two live pages share a global registration (for example `Get.put` without a tag, for two stacked `details` pages). Tag registrations with `PlayxScope.of(context).id`, keep the controller in the scope, or use a [route controller](controllers-and-views.md). ## `state.extra` is `null` on web It is not part of the URL, so it is lost on refresh, typed or shared URLs and deep links. Load by id when it is missing and use `state.extraAs()` to read it safely ([Web](web.md)). ## There is no back button on a page opened by URL Flutter's automatic `AppBar` back button only appears when there is something to pop. Use `PlayxBackButton` and a route `parentLocation` where needed ([Web](web.md#back-to-the-parent)). ## The browser tab title resets `MaterialApp` sets its own `title` whenever it rebuilds. Return `PlayxNavigation.pageTitle` from `onGenerateTitle` ([Browser tab titles](breadcrumbs.md#browser-tab-titles)). ## `await PlayxNavigation.offAndTo(...)` never finishes The returned future completes when the **new** page is popped, like `to`. Don't `await` it to wait for the navigation itself ([Navigation API](navigation-api.md#going-forward)). ## Lifecycle callbacks don't fire for dialogs or `Navigator.push` Only router navigation (pages in go_router's stack) affects the lifecycle. Dialogs, bottom sheets and routes pushed with `Navigator.push` don't hide the page underneath. ## Changing a query parameter doesn't re-run `onEnter` Only the path identifies a page. Changing the query string keeps the same page. Read parameters in the widget from `GoRouterState`, or navigate to a different path. ## Hot reload doesn't re-run `onInitApp` `onInitApp` runs at boot. Use a hot restart after changing it. ## Dependency conflict with `go_router` 3.0 depends on `go_router: ^17.5.0`. go_router 18 raises the minimum SDK to Flutter 3.44 and moves to `material_ui` / `cupertino_ui`; support for it will come in a later release. ## Still stuck? Open an issue with a minimal router that reproduces it: [github.com/playx-flutter/playx_navigation/issues](https://github.com/playx-flutter/playx_navigation/issues).