Joey Yi Zhao
Joey Yi Zhao

Reputation: 42426

How can I parse url parameter when using flutter navigator 2.0?

I am building flutter router based on this doc: https://techblog.geekyants.com/navigation-20-routing-on-flutter-web.

The question I have is that how can I get the url parameter on initial load? e.g. I have the url http://localhost:8080?id=1234/#/user which points to the path /user defined in RouterDelegate. I am able to open the related screen which is for /user but where should I parse the url parameter id?

Upvotes: 2

Views: 1893

Answers (2)

Vishal Singh
Vishal Singh

Reputation: 51

Whatever URL you enter in the browser it gets parsed in RouteInformationParser. In RouteInformationParser there is a method parseRouteInformation(), in that method you will get the RouteInformation and you can parse the RouteInformation as

final uri = Uri.parse(routeInformation.location);

Then you can check the "id" here. for eg -> let's say this is the route you have entered
http://localhost:8080?id=1234/#/user/2

 final id = uri.pathSegments.elementAt(1).toString();

This will give the id = 2;

For reference you can check the parseRouteInformation method code inside HomeRouteInformationParser (RouteInformationParser) class in the article that you have mentioned.

Upvotes: 2

Tharun K
Tharun K

Reputation: 1180

You can use the Uri class from dart:core

https://api.dartlang.org/apidocs/channels/stable/dartdoc-viewer/dart-core.Uri

ie: If url = http://localhost:8082/game.html?id=15&randomNumber=3.14

main() {
  print(Uri.base.toString()); // http://localhost:8082/game.html?id=15&randomNumber=3.14
  print(Uri.base.query);  // id=15&randomNumber=3.14
  print(Uri.base.queryParameters['randomNumber']); // 3.14
}

Upvotes: 2

Related Questions