go_router
the goal of the go_router package is to
simplify use of the router
in
flutter as specified
by the materialapp.router
constructor.
by default, it requires an implementation of the
routerdelegate
and
routeinformationparser
classes. these two implementations themselves imply the definition of a third
type to hold the app state that drives the creation of the
navigator
. you
can read an excellent blog post on these requirements on
medium.
this separation of responsibilities allows the flutter developer to implement a
number of routing and navigation policies at the cost of
complexity.
the purpose of the go_router is to use declarative routes to reduce complexity,
regardless of the platform you’re targeting (mobile, web, desktop), handling
deep linking from android, ios and the web while still allowing an easy-to-use
developer experience.
table of contents
- getting started
- declarative routing
- navigation
- initial location
- parameters
- sub-routes
- pushing pages
- redirection
- query parameters
- named routes
- custom transitions
- async data
- nested navigation
- deep linking
- url path strategy
- debugging your routes
- examples
- issues
getting started
to use the go_router package, follow these
instructions.
declarative routing
the go_router is governed by a set of routes which you specify as part of the
gorouter
constructor:
class app extends statelesswidget {
...
final _router = gorouter(
routes: [
goroute(
path: '/',
pagebuilder: (context, state) => materialpage<void>(
key: state.pagekey,
child: const page1page(),
),
),
goroute(
path: '/page2',
pagebuilder: (context, state) => materialpage<void>(
key: state.pagekey,
child: const page2page(),
),
),
],
...
);
}
in this case, we’ve defined two routes. each route path
will be matched
against the location to which the user is navigating. only a single path will be
matched, specifically the one that matches the entire location (and so it
doesn’t matter in which order you list your routes). the path
will be matched
in a case-insensitive way, although the case for parameters will
be preserved.
router state
a goroute
also contains a pagebuilder
function which is called to create the
page when a path is matched. the builder function is passed a state
object,
which is an instance of the gorouterstate
class that contains some useful
information:
gorouterstate property |
description | example 1 | example 2 |
---|---|---|---|
location |
location of the full route, including query params | /login?from=/family/f2 |
/family/f2/person/p1 |
subloc |
location of this sub-route w/o query params | /login |
/family/f2 |
path |
the goroute path |
/login |
family/:fid |
fullpath |
full path to this sub-route | /login |
/family/:fid |
params |
params extracted from the location | {'from': '/family/f1'} |
{'fid': 'f2'} |
error |
exception associated with this sub-route, if any |
exception('404') |
… |
pagekey |
unique key for this sub-route | valuekey('/login') |
valuekey('/family/:fid') |
you can read more about sub-locations/sub-routes and parametized
routes below but the example code above uses the pagekey
property as most of the example code does. the pagekey
is used to create a
unique key for the materialpage
or cupertinopage
based on the current path
for that page in the stack of pages, so it will uniquely identify
the page w/o having to hardcode a key or come up with one yourself.
error handling
in addition to the list of routes, the go_router needs an errorpagebuilder
function in case no page is found, more than one page is found or if any of the
page builder functions throws an exception, e.g.
class app extends statelesswidget {
...
final _router = gorouter(
...
errorpagebuilder: (context, state) => materialpage<void>(
key: state.pagekey,
child: errorpage(state.error),
),
);
}
the gorouterstate
object contains the location that caused the exception and
the exception
that was thrown attempting to navigate to that route.
initialization
with just a list of routes and an error page builder function, you can create an
instance of a gorouter
, which itself provides the objects you need to call the
materialapp.router
constructor:
class app extends statelesswidget {
app({key? key}) : super(key: key);
@override
widget build(buildcontext context) => materialapp.router(
routeinformationparser: _router.routeinformationparser,
routerdelegate: _router.routerdelegate,
);
final _router = gorouter(routes: ..., errorpagebuilder: ...);
}
with the router in place, your app can now navigate between pages.
navigation
to navigate between pages, use the gorouter.go
method:
// navigate using the gorouter
ontap: () => gorouter.of(context).go('/page2')
the go_router also provides a simplified means of navigation using dart
extension methods:
// more easily navigate using the gorouter
ontap: () => context.go('/page2')
the simplified version maps directly to the more fully-specified version, so you
can use either. if you’re curious, the ability to just call context.go(...)
and have magic happen is where the name of the go_router came from.
if you’d like to navigate via the link
widget,
that works, too:
link(
uri: uri.parse('/page2'),
builder: (context, followlink) => textbutton(
onpressed: followlink,
child: const text('go to page 2'),
),
),
if the link
widget is given a url with a scheme, e.g. https://flutter.dev
,
then it will launch the link in a browser. otherwise, it’ll navigate to the link
inside the app using the built-in navigation system.
you can also navigate to a named route, discussed below.
current location
if you want to know the current location, use the gorouter.location
property.
if you’d like to know when the current location changes, either because of
manual navigation or a deep link or a pop due to the user pushing the back
button, the gorouter
is a
changenotifier
,
which means that you can call addlistener
to be notified when the location
changes, either manually or via flutter’s builder widget for changenotifier
objects, the non-intuitively named
animatedbuilder
:
class routerlocationview extends statelesswidget {
const routerlocationview({key? key}) : super(key: key);
@override
widget build(buildcontext context) {
final router = gorouter.of(context);
return animatedbuilder(
animation: router,
builder: (context, child) => text(router.location),
);
}
}
or, if you’re using the provider package,
it comes with built-in support for re-building a widget
when a
changenotifier
changes with a type that is much more clearly suited for the
purpose.
initial location
if you’d like to set an initial location for routing, you can set the
initiallocation
argument of the gorouter
constructor:
final _router = gorouter(
routes: ...,
errorpagebuilder: ...,
initiallocation: '/page2',
);
the value you provide to initiallocation
will be ignored if your app is started
using deep linking.
parameters
the route paths are defined and implemented in the path_to_regexp
package, which gives you the ability
to include parameters in your route’s path
:
final _router = gorouter(
routes: [
goroute(
path: '/family/:fid',
pagebuilder: (context, state) {
// use state.params to get router parameter values
final family = families.family(state.params['fid']!);
return materialpage<void>(
key: state.pagekey,
child: familypage(family: family),
);
},
),
],
errorpagebuilder: ...,
]);
you can access the matched parameters in the state
object using the params
property.
dynamic linking
the idea of “dynamic linking” is that as the user adds objects to your app, each
of them gets a link of their own, e.g. a new family gets a new link. this is
exactly what route parameters enables, e.g. a new family has its own identifier
when can be a variable in your family route, e.g. path: /family/:fid
.
sub-routes
every top-level route will create a navigation stack of one page. to produce an
entire stack of pages, you can use sub-routes. in the case that a top-level
route only matches part of the location, the rest of the location can be matched
against sub-routes. the rules are still the same, i.e. that only a single
route at any level will be matched and the entire location much be matched.
for example, the location /family/f1/person/p2
, can be made to match multiple
sub-routes to create a stack of pages:
/ => homepage()
family/f1 => familypage('f1')
person/p2 => personpage('f1', 'p2') ← showing this page, back pops the stack ↑
to specify a set of pages like this, you can use sub-page routing via the
routes
parameter to the goroute
constructor:
final _router = gorouter(
routes: [
goroute(
path: '/',
pagebuilder: (context, state) => materialpage<void>(
key: state.pagekey,
child: homepage(families: families.data),
),
routes: [
goroute(
path: 'family/:fid',
pagebuilder: (context, state) {
final family = families.family(state.params['fid']!);
return materialpage<void>(
key: state.pagekey,
child: familypage(family: family),
);
},
routes: [
goroute(
path: 'person/:pid',
pagebuilder: (context, state) {
final family = families.family(state.params['fid']!);
final person = family.person(state.params['pid']!);
return materialpage<void>(
key: state.pagekey,
child: personpage(family: family, person: person),
);
},
),
],
),
],
),
],
errorpagebuilder: ...
);
the go_router will match the routes all the way down the tree of sub-routes to
build up a stack of pages. if go_router doesn’t find a match, then the error
handler will be called.
also, the go_router will pass parameters from higher level sub-routes so that
they can be used in lower level routes, e.g. fid
is matched as part of the
family/:fid
route, but it’s passed along to the person/:pid
route because
it’s a sub-route of the family/:fid
route.
pushing pages
in addition to the go
method, the go_router also provides a push
method.
both go
and push
can be used to build up a stack of pages, but in different
ways. the go
method does this by turning a single location into any number of
pages in a stack using sub-routes.
the push
method is used to push a single page onto the stack of existing
pages, which means that you can build up the stack programmatically instead of
declaratively. when the push
method matches an entire stack via sub-routes, it
will take the top-most page from the stack and push that page onto the stack.
you can also push a named route, discussed below.
redirection
sometimes you want your app to redirect to a different location. the go_router
allows you to do this at a top level for each new navigation event or at the
route level for a specific route.
top-level redirection
sometimes you want to guard pages from being accessed when they shouldn’t be,
e.g. when the user is not yet logged in. for example, assume you have a class
that tracks the user’s login info:
class logininfo extends changenotifier {
var _username = '';
string get username => _username;
bool get loggedin => _username.isnotempty;
void login(string username) {
_username = username;
notifylisteners();
}
void logout() {
_username = '';
notifylisteners();
}
}
you can use this info in the implementation of a redirect
function that you
pass as to the gorouter
constructor:
class app extends statelesswidget {
final logininfo = logininfo();
...
late final _router = gorouter(
routes: [
goroute(
path: '/',
pagebuilder: (context, state) => materialpage<void>(
key: state.pagekey,
child: homepage(families: families.data),
),
),
...,
goroute(
path: '/login',
pagebuilder: (context, state) => materialpage<void>(
key: state.pagekey,
child: const loginpage(),
),
),
],
errorpagebuilder: ...,
// redirect to the login page if the user is not logged in
redirect: (state) {
final loggedin = logininfo.loggedin;
final goingtologin = state.location == '/login';
// the user is not logged in and not headed to /login, they need to login
if (!loggedin && !goingtologin) return '/login';
// the user is logged in and headed to /login, no need to login again
if (loggedin && goingtologin) return '/';
// no need to redirect at all
return null;
},
);
}
in this code, if the user is not logged in and not going to the /login
path, we redirect to /login
. likewise, if the user is logged in but going to
/login
, we redirect to /
. if there is no redirect, then we just return
null
. the redirect
function will be called again until null
is returned to
enable multiple redirects.
to make it easy to access this info wherever it’s need in the app, consider
using a state management option like
provider to put the login info into the
widget tree:
class app extends statelesswidget {
final logininfo = logininfo();
// add the login info into the tree as app state that can change over time
@override
widget build(buildcontext context) => changenotifierprovider<logininfo>.value(
value: logininfo,
child: materialapp.router(...),
);
...
}
with the login info in the widget tree, you can easily implement your login
page:
class loginpage extends statelesswidget {
@override
widget build(buildcontext context) => scaffold(
appbar: appbar(title: text(_title(context))),
body: center(
child: column(
mainaxisalignment: mainaxisalignment.center,
children: [
elevatedbutton(
onpressed: () {
// log a user in, letting all the listeners know
context.read<logininfo>().login('test-user');
// go home
context.go('/');
},
child: const text('login'),
),
],
),
),
);
}
in this case, we’ve logged the user in and manually redirected them to the home
page. that’s because the go_router doesn’t know that the app’s state has
changed in a way that affects the route. if you’d like to have the app’s state
cause go_router to automatically redirect, you can use the refreshlistenable
argument of the gorouter
constructor:
class app extends statelesswidget {
final logininfo = logininfo();
...
late final _router = gorouter(
routes: ...,
errorpagebuilder: ...,
redirect: ...
// changes on the listenable will cause the router to refresh it's route
refreshlistenable: logininfo,
);
}
since the logininfo
is a changenotifier
, it will notify listeners when it
changes. by passing it to the gorouter
constructor, the go_router will
automatically refresh the route when the login info changes. this allows you to
simplify the login logic in your app:
onpressed: () {
// log a user in, letting all the listeners know
context.read<logininfo>().login('test-user');
// router will automatically redirect from /login to / because login info
//context.go('/');
},
the use of the top-level redirect
and refreshlistenable
together is
recommended because it will handle the routing automatically for you when the
app’s data changes.
route-level redirection
the top-level redirect handler passed to the gorouter
constructor is handy when you
want a single function to be called whenever there’s a new navigation event and
to make some decisions based on the app’s current state. however, in the case
that you’d like to make a redirection decision for a specific route (or
sub-route), you can do so by passing a redirect
function to the goroute
constructor:
final _router = gorouter(
routes: [
goroute(
path: '/',
redirect: (_) => '/family/${families.data[0].id}',
),
goroute(
path: '/family/:fid',
pagebuilder: ...,
],
errorpagebuilder: ...,
);
in this case, when the user navigates to /
, the redirect
function will be
called to redirect to the first family’s page. redirection will only occur on
the last sub-route matched, so you can’t have to worry about redirecting in the
middle of a location being parsed when you’re already on your way to another
page anyway.
parameterized redirection
in some cases, a path is parameterized, and you’d like to redirect with those
parameters in mind. you can do that with the params
argument to the state
object passed to the redirect
function:
goroute(
path: '/author/:authorid',
redirect: (state) => '/authors/${state.params['authorid']}',
),
multiple redirections
it’s possible to redirect multiple times w/ a single navigation, e.g. / => /foo => /bar
. this is handy because it allows you to build up a list of
routes over time and not to worry so much about attempting to trim each of them
to their direct route. furthermore, it’s possible to redirect at the top level
and at the route level in any number of combinations.
the only trouble you need worry about is getting into a loop, e.g. / => /foo => /
. if that happens, you’ll get an exception with a message like this:
exception: redirect loop detected: / => /foo => /
.
query parameters
sometimes you’re doing deep linking and you’d like a user to
first login before going to the location that represents the deep link. in that
case, you can use query parameters in the redirect function:
class app extends statelesswidget {
final logininfo = logininfo();
...
late final _router = gorouter(
routes: ...,
errorpagebuilder: ...,
// redirect to the login page if the user is not logged in
redirect: (state) {
final loggedin = logininfo.loggedin;
// check just the path in case there are query parameters
final goingtologin = state.subloc == '/login';
// the user is not logged in and not headed to /login, they need to login
if (!loggedin && !goingtologin) return '/login?from=${state.location}';
// the user is logged in and headed to /login, no need to login again
if (loggedin && goingtologin) return '/';
// no need to redirect at all
return null;
},
// changes on the listenable will cause the router to refresh it's route
refreshlistenable: logininfo,
);
}
in this example, if the user isn’t logged in, they’re redirected to /login
with a from
query parameter set to the deep link. the state
object has the
location
and the subloc
to choose from. the location
includes the query
parameters whereas the subloc
does not. since the /login
route may include
query parameters, it’s easiest to use the subloc
in this case (and using the
raw location
will cause a stack overflow, an exercise that i’ll leave to the
reader).
now, when the /login
route is matched, we want to pull the from
parameter
out of the state
object to pass along to the loginpage
:
goroute(
path: '/login',
pagebuilder: (context, state) => materialpage<void>(
key: state.pagekey,
// pass the original location to the loginpage (if there is one)
child: loginpage(from: state.params['from']),
),
),
in the loginpage
, if the from
parameter was passed, we use it to go to the
deep link location after a successful login:
class loginpage extends statelesswidget {
final string? from;
const loginpage({this.from, key? key}) : super(key: key);
@override
widget build(buildcontext context) => scaffold(
appbar: appbar(title: text(_title(context))),
body: center(
child: column(
mainaxisalignment: mainaxisalignment.center,
children: [
elevatedbutton(
onpressed: () {
// log a user in, letting all the listeners know
context.read<logininfo>().login('test-user');
// if there's a deep link, go there
if (from != null) context.go(from!);
},
child: const text('login'),
),
],
),
),
);
}
it’s still good practice to pass in the refreshlistenable
when manually
redirecting, as we do in this case, to ensure any change to the login info
causes the right routing to happen automatically, e.g. the user logging out will
cause them to be routed back to the login page.
named routes
when you’re navigating to a route with a location, you’re hardcoding the uri
construction into your app, e.g.
void _tap(buildcontext context, string fid, string pid) =>
context.go('/family/$fid/person/$pid');
not only is that error-prone, but the actual uri format of your app could change
over time. certainly redirection helps keep old uri formats working, but do you
really want various versions of your location uris lying willy-nilly around in
your code? the idea of named routes is to make it easy to navigate to a route
w/o knowing or caring what the uri format is. you can add a unique name to your
route using the goroute.name
parameter:
final _router = gorouter(
routes: [
goroute(
name: 'home',
path: '/',
pagebuilder: ...,
routes: [
goroute(
name: 'family',
path: 'family/:fid',
pagebuilder: ...,
routes: [
goroute(
name: 'person',
path: 'person/:pid',
pagebuilder: ...,
),
],
),
],
),
goroute(
name: 'login',
path: '/login',
pagebuilder: ...,
),
],
you don’t need to name any of your routes but the ones that you do name, you can
navigate to using the name and whatever params are needed:
void _tap(buildcontext context, string fid, string pid) =>
context.gonamed('person', {'fid': fid, 'pid': pid});
the gonamed
method will look up the route by name in a case-insensitive way,
construct the uri for you and fill in the params as appropriate. if you miss a
param, you’ll get an error. if you pass any extra params, they’ll be passed as
query parameters.
there is also a pushnamed
method that will look up the route by name, pull
the top page off of the stack and push that onto the existing stack of pages.
custom transitions
as you transition between routes, you get transitions based on whether
you’re using materialpage
or cupertinopage
; each of them implements the
transitions as defined by the underlying platform. however, if you’d like to
implement a custom transition, you can do so by using the customtransitionpage
provided with go_router:
goroute(
path: '/fade',
pagebuilder: (context, state) => customtransitionpage<void>(
key: state.pagekey,
child: const transitionspage(kind: 'fade', color: colors.red),
transitionsbuilder: (context, animation, secondaryanimation, child) =>
fadetransition(opacity: animation, child: child),
),
),
the transitionbuilder
argument to the customtransitionpage
is called when
you’re routing to a new route, and it’s your chance to return a transition
widget. the transitions sample shows off
four different kind of transitions, but really you can do whatever you want.
the customtransitionpage
constructor also takes a transitionsduration
argument in case you’d like to customize the duration of the transition as well
(it defaults to 300ms).
async data
sometimes you’ll want to load data asynchronously, and you’ll need to wait for
the data before showing content. flutter provides a way to do this with the
futurebuilder
widget that works just the same with the go_router as it always
does in flutter. for example, imagine you’ve got a repository
class that does
network communication when it looks up data:
class repository {
future<list<family>> getfamilies() async { /* network comm */ }
future<family> getfamily(string fid) async => { /* network comm */ }
...
}
now you can use the futurebuilder
to show a loading indicator while the data
is loading:
class app extends statelesswidget {
final repo = repository();
...
late final _router = gorouter(
routes: [
goroute(
path: '/',
pagebuilder: (context, state) => notransitionpage<void>(
key: state.pagekey,
child: futurebuilder<list<family>>(
future: repo.getfamilies(),
pagebuilder: (context, snapshot) {
if (snapshot.haserror)
return errorpage(snapshot.error as exception?);
if (snapshot.hasdata) return homepage(families: snapshot.data!);
return const center(child: circularprogressindicator());
},
),
),
routes: [
goroute(
path: 'family/:fid',
pagebuilder: (context, state) => notransitionpage<void>(
key: state.pagekey,
child: futurebuilder<family>(
future: repo.getfamily(state.params['fid']!),
pagebuilder: (context, snapshot) {
if (snapshot.haserror)
return errorpage(snapshot.error as exception?);
if (snapshot.hasdata)
return familypage(family: snapshot.data!);
return const center(child: circularprogressindicator());
},
),
),
routes: [
goroute(
path: 'person/:pid',
pagebuilder: (context, state) => notransitionpage<void>(
key: state.pagekey,
child: futurebuilder<familyperson>(
future: repo.getperson(
state.params['fid']!,
state.params['pid']!,
),
pagebuilder: (context, snapshot) {
if (snapshot.haserror)
return errorpage(snapshot.error as exception?);
if (snapshot.hasdata)
return personpage(
family: snapshot.data!.family,
person: snapshot.data!.person);
return const center(child: circularprogressindicator());
},
),
),
),
],
),
],
),
],
errorpagebuilder: (context, state) => materialpage<void>(
key: state.pagekey,
child: errorpage(state.error),
),
);
}
class notransitionpage<t> extends customtransitionpage<t> {
const notransitionpage({required widget child, localkey? key})
: super(transitionsbuilder: _transitionsbuilder, child: child, key: key);
static widget _transitionsbuilder(
buildcontext context,
animation<double> animation,
animation<double> secondaryanimation,
widget child) =>
child;
}
this is a simple case that shows a circular progress indicator while the data is
being loaded and before the page is shown.
the way transitions work, the outgoing page is shown for a little while before
the incoming page is shown, which looks pretty terrible when your page is doing
nothing but showing a circular progress indicator. i admit that i took the
coward’s way out and turned off the transitions so that things wouldn’t look
so bad in the animated screenshot. however, it would be nicer to keep the
transition, navigate to the page showing as much as possible, e.g. the appbar
,
and then show the loading indicator inside the page itself. in that case, you’ll
be on your own to show an error in the case that the data can’t be loaded. such
polish is left as an exercise for the reader.
nested navigation
sometimes you want to choose a page based on a route as well as the state of
that page, e.g. the currently selected tab. in that case, you want to choose not
just the page from a route but also the widgets nested inside the page. that’s
called “nested navigation”. the key differentiator for “nested” navigation is
that there’s no transition on the part of the page that stays the same, e.g. the
app bar stays the same as you navigate to different tabs on this tabview
:
of course, you can easily do this using the tabview
widget, but what makes
this nested “navigation” is that the location of the page changes, i.e. notice
the address bar as the user transitions from tab to tab. this makes it easy for
the user to capture a dynamic link for any object in the app,
enabling deep linking.
to use nested navigation using go_router, you can simply navigate to the same
page via different paths or to the same path with different parameters, with
the differences dictating the different state of the page. for example, to
implement that page with the tabview
above, you need a widget that changes the
selected tab via a parameter:
class familytabspage extends statefulwidget {
final int index;
familytabspage({required family currentfamily, key? key})
: index = families.data.indexwhere((f) => f.id == currentfamily.id),
super(key: key) {
assert(index != -1);
}
@override
_familytabspagestate createstate() => _familytabspagestate();
}
class _familytabspagestate extends state<familytabspage>
with tickerproviderstatemixin {
late final tabcontroller _controller;
@override
void initstate() {
super.initstate();
_controller = tabcontroller(
length: families.data.length,
vsync: this,
initialindex: widget.index,
);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
void didchangedependencies() {
super.didchangedependencies();
_controller.index = widget.index;
}
@override
widget build(buildcontext context) => scaffold(
appbar: appbar(
title: text(_title(context)),
bottom: tabbar(
controller: _controller,
tabs: [for (final f in families.data) tab(text: f.name)],
ontap: (index) => _tap(context, index),
),
),
body: tabbarview(
controller: _controller,
children: [for (final f in families.data) familyview(family: f)],
),
);
void _tap(buildcontext context, int index) =>
context.go('/family/${families.data[index].id}');
string _title(buildcontext context) =>
(context as element).findancestorwidgetofexacttype<materialapp>()!.title;
}
the familytabspage
is a stateful widget that takes the currently selected
family as a parameter. it uses the index of that family in the list of families
to set the currently selected tab. however, instead of switching the currently
selected tab to whatever the user clicks on, it uses navigation to get to that
index instead. it’s the use of navigation that changes the address in the
address bar. and, the way that the tab index is switched is via the call to
didchangedependencies
. because the familytabspage
is a stateful widget, the
widget itself can be changed but the state is kept. when that happens, the call
to didchangedependencies
will change the index of the tabcontroller
to match
the new navigation location.
to implement the navigation part of this example, we need a route that
translates the location into an instance of familytabspage
parameterized with
the currently selected family:
final _router = gorouter(
routes: [
goroute(
path: '/',
redirect: (_) => '/family/${families.data[0].id}',
),
goroute(
path: '/family/:fid',
pagebuilder: (context, state) {
final fid = state.params['fid']!;
final family = families.data.firstwhere((f) => f.id == fid,
orelse: () => throw exception('family not found: $fid'));
return materialpage<void>(
key: state.pagekey,
child: familytabspage(key: state.pagekey, currentfamily: family),
);
},
),
],
errorpagebuilder: ...,
);
the /
route is a redirect to the first family. the /family/:fid
route is the
one that sets up nested navigation. it does this by first creating an
instance of familytabspage
with the family that matches the fid
parameter.
and second, it uses state.pagekey
to signal to flutter that this is the same
page as before. this combination is what causes the router to leave the page
alone, to update the browser’s address bar and to let the tabview
navigate to
the new selection.
this may seem like a lot, but in summary, you need to do three things with the
page you create in your page builder to support nested navigation:
- use a
statefulwidget
as the base class of the thing you pass to
materialpage
(or whatever). - pass the same key value to the
materialpage
so that flutter knows that
you’re keeping the same state for yourstatefulwidget
-derived page;
state.pagekey
is handy for this. - as the user navigates, you’ll create the same
statefulwidget
-derived type,
passing in new data, e.g. which tab is currently selected. because you’re
using a widget with the same key, flutter will keep the state but swap out the
widget wrapping w/ the new data as constructor args. when that new widget wrapper is
in place, flutter will calldidchangedependencies
so that you can use the new
data to update the existing widgets, e.g. the selected tab.
this example shows off the selected tab on a tabview
but you can use it for
any nested content of a page your app navigates to.
keeping state
when doing nested navigation, the user expects that widgets will be in the same
state that they left them in when they navigated to a new page and return, e.g.
scroll position, text input values, etc. you can enable support for this by
using automatickeepaliveclientmixin
on a stateful widget. you can see this in
action in the familiyview
of the
nested_nav.dart
example:
class familyview extends statefulwidget {
const familyview({required this.family, key? key}) : super(key: key);
final family family;
@override
state<familyview> createstate() => _familyviewstate();
}
/// use the [automatickeepaliveclientmixin] to keep the state.
class _familyviewstate extends state<familyview>
with automatickeepaliveclientmixin {
// override `wantkeepalive` when using `automatickeepaliveclientmixin`.
@override
bool get wantkeepalive => true;
@override
widget build(buildcontext context) {
// call `super.build` when using `automatickeepaliveclientmixin`.
super.build(context);
return listview(
children: [
for (final p in widget.family.people)
listtile(
title: text(p.name),
ontap: () =>
context.go('/family/${widget.family.id}/person/${p.id}'),
),
],
);
}
}
to instruct the automatickeepaliveclientmixin
to keep the state, you need to
override wantkeepalive
to return true
and call super.build
in the state
class’s build
method, as show above.
notice that after scrolling to the bottom of the long list of children in the
hunting family, then going to another tab and then going to another page, when
you return to the list of huntings that the scroll position is maintained.
deep linking
flutter defines “deep linking” as “opening a url displays that screen in your
app.” anything that’s listed as a goroute
can be accessed via deep linking
across android, ios and the web. support works out of the box for the web, of
course, via the address bar, but requires additional configuration for android
and ios as described in the flutter
docs.
url path strategy
by default, flutter adds a hash (#) into the url for web apps:
the process for turning off the hash is
documented
but fiddly. the go_router has built-in support for setting the url path
strategy, however, so you can simply call gorouter.seturlpathstrategy
before
calling runapp
and make your choice:
void main() {
// turn on the # in the urls on the web (default)
// gorouter.seturlpathstrategy(urlpathstrategy.hash);
// turn off the # in the urls on the web
gorouter.seturlpathstrategy(urlpathstrategy.path);
runapp(app());
}
setting the path instead of the hash strategy turns off the # in the urls:
if your router is created as part of the construction of the widget passed to
the runapp
method, you can use a shortcut to set the url path strategy by
using the urlpathstrategy
parameter of the gorouter
constructor:
// no need to call gorouter.seturlpathstrategy() here
void main() => runapp(app());
/// sample app using the path url strategy, i.e. no # in the url path
class app extends statelesswidget {
...
final _router = gorouter(
routes: ...,
errorpagebuilder: ...,
// turn off the # in the urls on the web
urlpathstrategy: urlpathstrategy.path,
);
}
finally, when you deploy your flutter web app to a web server, it needs to be
configured such that every url ends up at your flutter web app’s index.html
,
otherwise flutter won’t be able to route to your pages. if you’re using firebase
hosting, you can configure
rewrites to
cause all urls to be rewritten to index.html
.
if you’d like to test your release build locally before publishing, and get that
cool redirect to index.html
feature, you can use flutter run
itself:
$ flutter run -d chrome --release lib/url_strategy.dart
note that you have to run this command from a place where flutter run
can find
the web/index.html
file.
of course, any local web server that can be configured to redirect all traffic
to index.html
will do, e.g.
live-server.
debugging your routes
because go_router asks that you provide a set of paths, sometimes as fragments
to match just part of a location, it’s hard to know just what routes you have in
your app. in those cases, it’s handy to be able to see the full paths of the
routes you’ve created as a debugging tool, e.g.
gorouter: known full paths for routes:
gorouter: => /
gorouter: => /family/:fid
gorouter: => /family/:fid/person/:pid
gorouter: known full paths for route names:
gorouter: home => /
gorouter: family => /family/:fid
gorouter: person => /family/:fid/person/:pid
likewise, there are multiple ways to navigate, e.g. context.go()
,
context.gonamed()
, context.push()
, context.pushnamed()
, the link
widget,
etc., as well as redirection, so it’s handy to be able to see how that’s going
under the covers, e.g.
gorouter: setting initial location /
gorouter: location changed to /
gorouter: looking up named route "person" with {fid: f2, pid: p1}
gorouter: going to /family/f2/person/p1
gorouter: location changed to /family/f2/person/p1
finally, if there’s an exception in your routing, you’ll see that in the debug
output, too, e.g.
gorouter: exception: no routes for location: /foobarquux
to enable this kind of output when your gorouter
is first created, you can use
the debuglogdiagnostics
argument:
final _router = gorouter(
routes: ...,
errorpagebuilder: ...,
// log diagnostic info for your routes
debuglogdiagnostics: true,
);
this parameter defaults to false
, which produces no output.
examples
you can see the go_router in action via the following examples:
main.dart
: define a basic routing policy using a
set of declarativegoroute
objectsinit_loc.dart
: start at a specific location
instead of home (/
), which is the defaultsub_routes.dart
: provide a stack of pages
based on a set of sub routespush.dart
: provide a stack of pages
based on a series of calls tocontext.push()
redirection.dart
: redirect one route to
another based on changing app statequery_params.dart
: optional query
parameters will be passed to all page buildersnamed_routes.dart
: navigate via name
instead of location uritransitions.dart
: use custom transitions
during routingasync_data.dart
: async data lookupnested_nav.dart
: include information about
children on a page as part of the route pathurl_strategy.dart
: turn off the # in the
flutter web urlstate_restoration.dart
: test to ensure
that go_router works with state restoration (it does)cupertino.dart
: test to ensure that go_router
works with the cupertino design language as well as material (it does)books/main.dart
: update of the
navigation_and_routing
sample to use go_router
you can run these examples from the command line like so (from the example
folder):
$ flutter run lib/main.dart
or, if you’re using visual studio code, a launch.json
file has been provided with these examples configured.
issues
do you have an issue with or feature request for go_router? log it on the issue
tracker.
Comments are closed.