Download this source code for
5 USD


Download this source code for
5 USD


Download this source code for
5 USD


Download this source code for
5 USD

nav_stack

a simple but powerful path-based routing system, based on materialapp.router (nav 2.0). it has browser / deeplink support and maintains a history stack as new routes are added.

internally navstack uses an indexedstack to maintain a stateful list of routes which are defined declaratively and bound to the current materialapp.router path. it also provides a flexible imperative api for changing the path and modifying the history stack.

�� installation

dependencies:
  nav_stack: ^0.0.1

⚙ import

import 'package:nav_stack/nav_stack.dart';

��️ basic usage

hello navstack

navstack wraps materialapp, so you can include it as the root-element in your app:

runapp(
  navstack(stackbuilder: (_, controller){
        // path stack does all the heavy lifting when it comes to arranging our routes
        // read more here: https://pub.dev/packages/path_stack#defining-paths
      return pathstack(
        routes: {
          ["/page1"]: container(color: colors.red).buildstackroute(),
          ["/page2"]: container(color: colors.green).buildstackroute(),
          // nesting allows you to type relative paths, and to also wrap sub-sections in their own menus/scaffold
          ["/page3/"]: pathstack(
            routes: {
               // paths can have multiple entries, allowing aliases,
               // using "" alias here allows this route to match "page3/" or "page3/subpage1"
              ["subpage1", ""]: container(color: colors.orange).buildstackroute(),
              ["subpage2"]: stackroutebuilder(builder: (_, __) => container(color: colors.purple)), //matches: /page3/subpage2
            },
          ).buildstackroute()});
}
}));
...
// change path using a simple api:
void showpage1() => navstack.of(context).path = "/page1";
void showsubpage2() => navstack.of(context).path = "/page3/subpage2";

this might not look like much, but there is a lot going on here.

  • this is fully bound to the browser path,
  • it will also receive deep-link start up values on any platform,
  • it provides a controller which you can use to easily change the global path at any time,
  • all routes are persistent, maintaining their state as you navigate between them (optional)

buildstackroute() vs stackroutebuilder?

each entry in the pathstack requires a stackroutebuilder() but to increase readability, we have added a .buildstackroute() extension method on all widgets. the only difference between the two, is that the full stackroutebuilder allows you to inject args directly into your view using it’s builder method.

when your view does not require args, then the extensions tend to be more readable:

// these calls are identical
["/login"]: loginscreen().buildstackroute(),
vs
["/login"]: stackroutebuilder(builder: (_, __) => loginscreen()),

customizing materialapp

navstack creates a default materialapp.router internally, but you can provide a custom one if you need to modify the settings. just use the appbuilder and pass along the provided parser and delegate instances:

runapp(navstack(
  appbuilder: (delegate, parser) => materialapp.router(
    routeinformationparser: parser,
    routerdelegate: delegate,
    debugshowcheckedmodebanner: false,
  ),
  stackbuilder: ...)

note: do not wrap a second materialapp around navstack or you will break all browser support and deep-linking.

nesting

one of the key features of this package is that it has top-level support for wrapping child routes in a shared widget (aka ‘nesting’). to supply a custom scaffold around all child routes use the scaffoldbuilder. for example, a classic ‘tab style’ app could look like:

runapp(navstack(
  stackbuilder: (context, controller) => pathstack(
    // use scaffold builder to wrap all our pages in a stateful tab-menu
    scaffoldbuilder: (_, stack) => _tabscaffold(["/home", "/profile"], child: stack),
    routes: {
      ["/home"]: loginscreen().buildstackroute(),
      ["/profile"]: profilescreen().buildstackroute(),
})));
...
class _tabscaffold extends statelesswidget {
  ...
  widget build(buildcontext context) {
    return column(
      children: [
        // the current route
        expanded(child: child),
        // a row of btns that call `navstack.of(context).path = value` when pressed
        row(children: [ expanded(child: textbutton(...)), expanded(child: textbutton(...)) ]),
      ]);}
}

additionally, you can nest pathstack widgets to create sub-sections. each with their own scaffold. for example here we wrap a nested-scaffold around all routes in the “/settings/” section of our app:

runapp(navstack(
  stackbuilder: (context, controller) {
    return pathstack(
      scaffoldbuilder: (_, stack) => outertabscaffold(stack),
      routes: {
        ["/login", "/"]: loginscreen().buildstackroute(),
        // nest a 2nd pathstack so all settings pages can share a secondary tab menu
        ["/settings/"]: pathstack(
          scaffoldbuilder: (_, stack) => innertabscaffold(stack),
          routes: {
            ["profile"]: profilescreen().buildstackroute(),
            ["alerts"]: alertsscreen().buildstackroute(),
          },
        ).buildstackroute(),
},);},));

path parsing rules:

there are a number of rules that determine how paths are routed:

  • routes with no trailing slash must an exact match:
    • eg, /details matches only /details not /details/, /details/12 or /details/?id=12
    • a special case is made for / which is always an exact match
  • routes with a trailing slash, will accept a suffix,
    • eg, /details/ matches any of /details/, /details/12, /details/id=12&foo=99 etc
    • this allows endless levels of nesting and relative routes
  • if route has multiple paths, only the first one will be considered for the suffix check
    • eg, ["/details", "/details/"] requires exact match on either path
    • eg, ["/details/", "/details"] allows suffix on either path

defining path and query-string arguments

both path-based (/billing/88/99) or query-string (/billing/?foo=88&bar=99) args are supported.

in order to parse the args before they enter your view, you can use the stackroutebuilder().
consuming path-based args looks like:

["billing/:foo/:bar"]:
    stackroutebuilder(builder: (_, args) => billingpage(foo: args["foo"], bar: args["bar"])),

consuming query-string args looks like:

["billing/"]:
    stackroutebuilder(builder: (_, args) => billingpage(id: "${args["foo"]}_${args["bar"]}")),

if you would like to access the args from within your view, and parse them there, you can just do:

navstack.of(context).args;

for more information on how paths are parsed check out https://pub.dev/packages/path_to_regexp.
to play with different routing schemes, you can use this demo: https://path-to-regexp.web.app/

imperative api

navstack offers a strong imperative api for interacting with your navigation state.

  • navstackcontroller can be looked up at anytime with navstack.of(context)
  • navstack.path to change the global routing path
  • navstack.history to access the history of path entries so far, you can modify and re-assign this list as needed
  • navstack.goback() to go back one level in the history
  • navstack.popuntil(), navstack.popmatching(), navstack.replacepath() etc

keeping it old school

importantly, you can still make full use of the old navigator.push(), showdialog, showbottomsheet apis, just be aware that none of these routes will be reflected in the navigation path. this can be quite handy for user-flows that do not necessarily need to be bound to browser history.

important: the entire navstack exists within a single pageroute. this means that calls to navigator.of(context).pop() from within the navstack children will be ignored. however, you can still use .pop() them from within dialogs, bottomsheets or full-screen pageroutes triggered with navigator.push().

�� advanced usage

in addition to basic nesting and routing, navstack supports advanced features including aliases, regular expressions and route guards.

regular expressions

one powerful aspect of the path-base args is you can append regular expressions to the match.

  • eg, a route of /user/:foo(d+) will match ‘/user/12’ but not ‘/user/alice’
  • don’t worry if you don’t know regular expressions, they are optional, and best used for advanced use cases

for more details on this parsing, check out the pathtoregexp docs:
https://pub.dev/packages/path_to_regexp

aliases

each route entry can have multiple paths allowing it to match any of them. for example, we can setup a route to match both /home and /:

["/home", "/"]: loginscreen().buildstackroute(),

or a route that accepts optional named params:

["/messages/", "/messages/:messageid"]: // matches both "/messages/" and "messages/99"
    stackroutebuilder(builder: (_, args) => messageview(args["messageid"] ?? "")

route guards

guards allow you to intercept a navigation event on a per-route basis. commonly used to prevent deep-links into unauthorized app sections.

to do this you can use the stackroutebuilder.onbeforeenter callback to run your own custom logic, and decide whether to block the change.

for example, this guard will redirect to loginscreen and show a warning dialog (but you can do whatever you want):

// you can use either the `buildstackroute` or `stackroutebuilder` to add guards
["/admin"]: adminpanel().buildstackroute(onbeforeenter: (_, __) => guardauthsection()),
["/admin"]: stackroutebuilder(builder: (_, __) => adminpanel(), onbeforeenter: (_, __) => guardauthsection() )
...
bool guardauthsection() {
  if (!appmodel.isloggedin){
   // schedule a redirect next frame
   navstack.of(context).redirect("/login", () => showauthwarningdialog(context));
   return false; // if we return false, the original route will not be entered.
  }
  return true;
}

since guards are just functions, you can easily re-use them across routes, and they can also be applied to entire sections by nesting a pathstack component.

putting it together

here’s a a more complete example showing nested stacks, and an entire section that requires the user to be logged in. otherwise they are redirected to /login:

bool isloggedin = false;

return navstack(
  stackbuilder: (context, controller) {
    return pathstack(
      scaffoldbuilder: (_, stack) => _myscaffold(stack),
      routes: {
        ["/login", "/"]: loginscreen().buildstackroute(),
        ["/in/"]: pathstack(
          routes: {
            ["profile/:profileid"]:
                stackroutebuilder(builder: (_, args) => profilescreen(profileid: args["profileid"] ?? "")),
            ["settings"]: settingsscreen().buildstackroute(),
          },
        ).buildstackroute(onbeforeenter: (_) {
          if (!isloggedin) controller.redirect("/login", () => showauthwarning(context));
          return isloggedin; // if we return false, the route will not be entered.
        }),
      },
    );
  },
);
...
void handleloginpressed() => navstack.of(context).path = "/login";
void showprofile() => navstack.of(context).path = "/in/profile/23"; // blocked
void showsettings() => navstack.of(context).path = "/in/settings"; // blocked

note: string literals ("/home") are used here for brevity and clarity. in real usage, it is recommended you give each page it’s own path property like homepage.path or loginscreen.path. this makes it much easier to construct and share links from other sections in your app: controller.path = "${settingspage.path}{profilepage.path}$profileid"

there are many other options you can provide to the pathstack, including unknownpathbuilder, transitionbuilder and, basepath. for an exhaustive list, check out this example:


Download this source code for
5 USD


Download this source code for
5 USD


Download this source code for
5 USD


Download this source code for
5 USD

Comments are closed.