Episode - 21 Create a Route Information Parser
Now that our Navigation state is ready let us parse the infromation that we get from our navigation. We are going to use the RouteInformationParser for this. In the Router directory create a new file called as book_router_parser.dart and in this file create a BookRouterParser class which extends RouteInformationParser with our AppLink Type like this.
class BookRouterParser extends RouteInformationParser<AppLink>{}
In this class we are going to override two methods from our RoutInformationParser class.
- parseRouteInformation
- restoreRouteInformation
The parseRouteInformation contains the RouteInformation that we pass as a parameter into function. This contains all the information of our route. We use this RouteInformation to create an AppLink from the fromLocation method that we had created in our AppLink Class. This will convert the URL String into AppLink object which can be used in our app.
For that
@override
Future<AppLink> parseRouteInformation(
RouteInformation routeInformation) async {
final link = AppLink.fromLocation(routeInformation.location);
print(link.location);
return link;
}
The second function called as the restoreRouteInformation takes an AppLink as an object and converts it into the String URL. We pass the applink as the parameter in this function.
@override
RouteInformation restoreRouteInformation(AppLink appLink) {
final location = appLink.toLocation();
return RouteInformation(location: location);
}
Now that we have created the RouteInformationParser. It is now time to connect the the parser with our RouterDelegate. So that what ever information the RouteParser gets can be passed to the RouterDelegate.
- open main.dart file and create an instance of our route parser
final bookRouterParser = BookRouterParser();
Dont forget to import the BookRouterParser class on the top. Now scroll down to materialApp section and replace the MaterialApp with MaterialApp.router and pass all the properties there as follows
MaterialApp.router(
routeInformationParser: bookRouteParser,
backButtonDispatcher: RootBackButtonDispatcher(),
routerDelegate: _bookRouterDelegate,
));
Here we have set the routeInformationParser as bookRouterParser that we have created. Just like before we set the routerDelegate as the _bookRouterDeledate
The user enters the URl in the browers address bar. The routeInformationParser parses the route into our navigation state, which is an instance of AppLink. Now based on the navigation state, RouterDelegate uodates the app state so that the new changes can be visible.