Goal: As a user, I want to navigate through pages without reloading the application.
Keywords: router, url pattern
-
Add
route
dependency inpubspec.yaml
dependencies: route: any
-
Create a new custom element
x-route
(Hints)
-
Create
route.html
androute.dart
file. Copy this class as it is:import 'package:polymer/polymer.dart'; import 'package:route/client.dart'; @CustomTag('x-route') class XRoute extends PolymerElement { XRoute.created() : super.created() { var router = new Router() ..addHandler(gamesUrl, _routeHandler(gamesUrl)) ..addHandler(gameUrl, _routeHandler(gameUrl)) ..addHandler(newGameUrl, _routeHandler(newGameUrl)) ..listen(); route = new Route(gamesUrl); } final gamesUrl = new UrlPattern(r'/(.*)#/games'); final gameUrl = new UrlPattern(r'/(.*)#/games/(\d+)'); final newGameUrl = new UrlPattern(r'/(.*)#/games/new'); @observable Route route; Handler _routeHandler(UrlPattern url) => (String path) { print("Route changed: $url - $path"); route = new Route(url, url.parse(path)); }; int asInt(String value) => int.parse(value); } class Route { final UrlPattern url; final List params; Route(this.url, [this.params = const []]); operator [](int index) => index < params.length ? params[index] : null; }
- Explore this class
- When one of registered
UrlPattern
is handled on url that has changed, theroute
attribute is updated. There is already three registered patterns:#/games
: to show the games list#/game/1
: to edit the game with id=1#/games/new
: to create a new game
- The
Route
class contains the handledUrlPattern
and the parsed parameters. - In databindings, parameters can be retrieved with this syntax:
route[1]
where1
is the group index in regex
- In
route.html
, create two contidionnal templates to switch betweenx-games
element andx-game-edit
.
- Check if the current
route.url
is the expectedUrlPattern
- Don't forget to set the
gameId
attribute from the parsed parameters
- In
index.html
, usex-route
instead ofx-game-edit
andx-games
. - Now you can bookmark your games list!
Hints:
- Read sample of Client routing