I want to create a shop web application with flutter. I need to add the subdirectory to the URL of the app. For example, if my app address is https://example.app/
, then I want to add https://example.app/500
that 500 is one of my product IDs. How can I do that and how to detect that id?
CodePudding user response:
Recently we developed one web app in Flutter. In that we were managing category with product id.
For that I have used auto_route: ^3.1.3
dependency.
Here is the sample, How you can create routes.
class UserRoute extends PageRouteInfo {
UserRoute({List<PagerouteInfo> children}) :
super(
name,
path: '/user/:id',
initialChildren: children);
static const String name = 'UserRoute';
}
Check documentation for more info.
CodePudding user response:
In this case, it is using navigator 2
. You need to extend RouteInformationParser
and check pathSegments
.
On your main class, App
will return MaterialApp.router
and need to provide routerDelegate
and routeInformationParser
.
return MaterialApp.router(
routeInformationParser: _routeInformationParser,
routerDelegate: _routerDelegate,
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
);
_routeInformationParser
will be extended from RouteInformationParser
and _routerDelegate
will extend RouterDelegate
.
Based on https://example.app/500
it is having pathSegments.length == 2
If will be handled like
if (uri.pathSegments.length == 2) {
if (uri.pathSegments[0] != 'details') return AppRoutePath.unknown();// recheck
final id = int.tryParse(uri.pathSegments[1]);
if (id == null) return AppRoutePath.unknown();
return AppRoutePath.details(id);
}
You can find my practice demo here using navigator2. Also there are great packages for it like, auto_route as @Pratik Butani described , go_router etc.