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

routemaster

hello! routemaster is an easy-to-use router for flutter, which wraps over navigator 2.0… and has a silly name.

build codecov
pub

features

  • simple declarative mapping from urls to pages
  • easy-to-use api: just routemaster.of(context).push('/page')
  • really easy nested navigation support for tabs
  • multiple route maps: for example one for a logged in user, another for logged out
  • observers to easily listen to route changes
  • covered by over 250 unit, widget and integration tests

here’s the entire routing setup needed for an app featuring tabs and pushed routes:

final routes = routemap(
  routes: {
    '/': (_) => cupertinotabpage(
          child: homepage(),
          paths: ['/feed', '/settings'],
        ),

    '/feed': (_) => materialpage(child: feedpage()),
    '/settings': (_) => materialpage(child: settingspage()),
    '/feed/profile/:id': (info) => materialpage(
      child: profilepage(id: info.pathparameters['id'])
    ),
  }
);

void main() {
  runapp(
      materialapp.router(
        routerdelegate: routemasterdelegate(routesbuilder: (context) => routes),
        routeinformationparser: routemasterparser(),
      ),
  );
}

and then to navigate:

routemaster.of(context).push('/feed/profile/1');

…you can see this in action in this simple app example.

there’s also a more advanced example.

i would love any feedback you have! please create an issue for api feedback.

documentation

begin with the quick start below, but also see the api reference, wiki and faqs.


quick start api tour

overview

routemaster generates pages based on the current path. this is the key concept of its path-base routing. path structure matters.

it uses the path to decide where a page should be pushed. this means the path needs to match your intended page hierarchy.

for example:

'/tabs': (route) => tabpage(child: homepage(), paths: ['one', 'two']),

// first tab default page
'/tabs/one': (route) => materialpage(child: tabonepage()),

// second tab default page
'/tabs/two': (route) => materialpage(child: tabtwopage()),

// second tab sub-page: will be displayed in the 2nd tab because it
// starts with '/tabs/two'
'/tabs/two/subpage': (route) => materialpage(child: tabtwopage()),

// not a tab page: will not be displayed in in a tab
// because the path doesn't start with '/tabs/one' or '/tabs/two'
'/tabs/notinatab': (route) => materialpage(child: nottabpage()),

any child paths that begin with /tabs/one or /tabs/two will be pushed into the correct tab.

when navigating to /tabs/two/subpage, the tabpage will be asked “hey, do you know how to handle this path?” and it’ll go “sure! it starts with /tabs/two, so it goes in my second tab”.

however, navigating to /tabs/notinatab will not be displayed in a tab, but pushed on top of the tab bar.

tabpage will be all “yeah sorry, no idea what to do with that, doesn’t match any of my tab paths” and its parent will be asked to hande it.

path hierarchy matters, for example changing where dialogs are displayed.

routing

basic app routing setup

materialapp.router(
  routerdelegate: routemasterdelegate(
    routesbuilder: (context) => routemap(routes: {
      '/': (routedata) => materialpage(child: pageone()),
      '/two': (routedata) => materialpage(child: pagetwo()),
    }),
  ),
  routeinformationparser: routemasterparser(),
)

navigate from within pages

routemaster.of(context).push('relative-path');
routemaster.of(context).push('/absolute-path');

routemaster.of(context).replace('relative-path');
routemaster.of(context).replace('/absolute-path');

path parameters

// path '/products/123' will result in productpage(id: '123')
routemap(routes: {
  '/products/:id': (route) => materialpage(
        child: productpage(id: route.pathparameters['id']),
      ),
  '/products/mypage': (route) => materialpage(mypage()),
})

note that routes without path parameters have priority, so in the above example
/products/mypage will show mypage.

query parameters

// path '/search?query=hello' results in searchpage(query: 'hello')
routemap(routes: {
  '/search': (route) => materialpage(
        child: searchpage(query: route.queryparameters['query']),
      ),
})

get current path info within a widget

routedata.of(context).path; // full path: '/product/123?query=param'
routedata.of(context).pathparameters; // map: {'id': '123'}
routedata.of(context).queryparameters; // map: {'query': 'param'}

tabs

setup:

routemap(
  routes: {
    '/': (route) => tabpage(
          child: homepage(),
          paths: ['/feed', '/settings'],
        ),
    '/feed': (route) => materialpage(child: feedpage()),
    '/settings': (route) => materialpage(child: settingspage()),
  },
)

main page:

class homepage extends statelesswidget {
  @override
  widget build(buildcontext context) {
    final tabpage = tabpage.of(context);

    return scaffold(
      appbar: appbar(
        bottom: tabbar(
          controller: tabpage.controller,
          tabs: [
            tab(text: 'feed'),
            tab(text: 'settings'),
          ],
        ),
      ),
      body: tabbarview(
        controller: tabpage.controller,
        children: [
          for (final stack in tabpage.stacks) pagestacknavigator(stack: stack),
        ],
      ),
    );
  }
}

cupertino tabs

setup:

routemap(
  routes: {
    '/': (route) => cupertinotabpage(
          child: homepage(),
          paths: ['/feed', '/settings'],
        ),
    '/feed': (route) => materialpage(child: feedpage()),
    '/settings': (route) => materialpage(child: settingspage()),
  },
)

main page:

class homepage extends statelesswidget {
  @override
  widget build(buildcontext context) {
    final tabstate = cupertinotabpage.of(context);

    return cupertinotabscaffold(
      controller: tabstate.controller,
      tabbuilder: tabstate.tabbuilder,
      tabbar: cupertinotabbar(
        items: [
          bottomnavigationbaritem(
            label: 'feed',
            icon: icon(cupertinoicons.list_bullet),
          ),
          bottomnavigationbaritem(
            label: 'settings',
            icon: icon(cupertinoicons.search),
          ),
        ],
      ),
    );
  }
}

guarded routes

show default not found page if validation fails:

'/protected-route': (route) => 
    canuseraccesspage()
      ? materialpage(child: protectedpage())
      : notfound()

redirect to another page if validation fails (changes url):

'/protected-route': (route) => 
    canuseraccesspage()
      ? materialpage(child: protectedpage())
      : redirect('/no-access'),

show another page if validation fails (doesn’t change url):

'/protected-route': (route) => 
    canuseraccesspage()
      ? materialpage(child: protectedpage())
      : materialpage(child: customnoaccesspage())

404 page

default page to shown on unknown url:

routemap(
    onunknownroute: (route, context) {
        return materialpage(child: notfoundpage());
    },
    routes: {
        '/': (_) => materialpage(child: homepage()),
    },
)

redirect

redirect one route to another:

routemap(routes: {
    '/one': (routedata) => materialpage(child: pageone()),
    '/two': (routedata) => redirect('/one'),
})

redirect all routes to login page, for a logged-out route map:

routemap(
  onunknownroute: (_) => redirect('/'),
  routes: {
    '/': (_) => materialpage(child: loginpage()),
  },
)

passing path parameters from original to the redirect path:

routemap(routes: {
    '/user/:id': (routedata) => materialpage(child: userpage(id: id)),
    '/profile/:uid': (routedata) => redirect('/user/:uid'),
})

swap routing map

you can swap the entire routing map at runtime.

this is particularly useful for different pages depending on whether the user is logged in:

final loggedoutmap = routemap(
  onunknownroute: (route, context) => redirect('/'),
  routes: {
    '/': (_) => materialpage(child: loginpage()),
  },
);

final loggedinmap = routemap(
  routes: {
    // regular app routes
  },
);

materialapp.router(
  routerdelegate: routemasterdelegate(
    routesbuilder: (context) {
			// this will rebuild when appstate changes
      final appstate = provider.of<appstate>(context);
      return appstate.isloggedin ? loggedinmap : loggedoutmap;
    },
  ),
  routeinformationparser: routemasterparser(),
);

navigation observers

class myobserver extends routemasterobserver {
	// routemasterobserver extends navigatorobserver and
	// receives all nested navigator events
  @override
  void didpop(route route, route? previousroute) {
    print('popped a route');
  }

	// routemaster-specific observer method
  @override
  void didchangeroute(routedata routedata, page page) {
    print('new route: ${routedata.path}');
  }
}

materialapp.router(
  routerdelegate: routemasterdelegate(
    observers: [myobserver()],
    routesbuilder: (_) => routemap,
  ),
  routeinformationparser: routemasterparser(),
);

navigate without a context

app.dart

final routemaster = routemasterdelegate(
  routesbuilder: (context) => routemap,
);

materialapp.router(
  routerdelegate: routemaster,
  routeinformationparser: routemasterparser(),
)

my_widget.dart

import 'app.dart';

void ontap() {
  routemaster.push('/blah');
}

hero animations

hero animations will work automatically on the top-level navigator (assuming you’re using materialapp or cupertinoapp).

for any child navigators, you’ll need to wrap pagestacknavigator in a herocontrollerscope, like this:

herocontrollerscope(
  controller: materialapp.creatematerialherocontroller(),
  child: pagestacknavigator(
    stack: pagestack,
  )
)

design goals

  • integrated: work with the flutter navigator 2.0 api, don’t try to replace it. try to have a very flutter-like api.
  • usable: design around user scenarios/stories, such as the ones in the flutter storyboardsee here for examples.
  • opinionated: don’t provide 10 options to achieve a goal, but be flexible for all scenarios.
  • focused: just navigation, nothing else. for example, no dependency injection.

this project builds on page_router.

name

named after the original routemaster:

a photo of a routemaster bus

(photo by chris sampson, licensed under cc by 2.0)


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.