2

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?

2 Answers 2

2

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
}
Sign up to request clarification or add additional context in comments.

Comments

2

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.

3 Comments

I tried the method with this url http://localhost:8080?id=1234/#/user/2, but after type in the browser, it becomes http://localhost:8080/#/user/2 and id parameter is wipped out.
I think thats not the right format of URL. Pramas should come after path resource. you can try this localhost:8080/#/user/?id=1234. Then you can get the "id" param as final uri = Uri.parse(routeInformation.location); id = uri.queryParameters["id"]; (as mentioned in one of the answers here)
or you can keep it like that just move the "#" localhost:52161/#/?id=12345/user here on doing id = uri.queryParameters["id"]; you will get id = "12345/user" and you can get id out of it -> uri.queryParameters["id"].split("/")[0]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.