Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a named route have URL parameters in flutter web?

I'm building a web-app which needs to have a route that gets a post ID and then it will fetch the post using the ID.

How can I have URL arguments let's say /post/:id so id is the argument

My app looks like that currently:

class MyApp extends StatelessWidget {   @override   Widget build(BuildContext context) {     return MaterialApp(       // title: "Paste",       initialRoute: "/",       theme: ThemeData(           primarySwatch: Colors.green,           primaryColor: Colors.blue       ),       routes: {         "/": (context) => HomePage(),         "/post": (context) => PastieRoute()       },       debugShowCheckedModeBanner: false     );   } } 

EDIT: This is what I tried according to @BloodLoss and for some reason I don't get anything to the console when accessing localhost:8080/post?id=123

class MyApp extends StatelessWidget {   @override   Widget build(BuildContext context) {     return MaterialApp(       initialRoute: "/",       routes: {         "/": (context) => HomePage(),         "/post": (context) => PastieRoute()       },       onGenerateRoute: (settings) {         if (settings.name == "/post") {           print(settings.arguments); // Doesn't fire :(            return MaterialPageRoute(             builder: (context) {               // TODO             }           );         }       },       debugShowCheckedModeBanner: false     );   } } 
like image 292
TheOnlyArtz Avatar asked Aug 19 '19 08:08

TheOnlyArtz


People also ask

How do you pass a URL in Flutter?

You can use go_router package from https://pub.dev. it is made by flutter team for this kind of routing. class App extends StatelessWidget { App({Key? key}) : super(key: key); @override Widget build(BuildContext context) => MaterialApp.


1 Answers

tl;dr

//in your example: settings.name = "/post?id=123" final settingsUri = Uri.parse(settings.name); //settingsUri.queryParameters is a map of all the query keys and values final postID = settingsUri.queryParameters['id']; print(postID); //will print "123" 

Drilldown

In a perfect world you would access queryParameters with Uri.base.queryParameters because:

Uri.base

Returns the natural base URI for the current platform. When running in a browser this is the current URL of the current page (from window.location.href). When not running in a browser this is the file URI referencing the current working directory.

But currently there is an issue in flutter where you have #/ in your path which messes the Uri.base interpretation of the Uri.
Follow the issue #33245 until this matter is addressed and you will be able to use Uri.base.queryParameters

like image 141
Alex.F Avatar answered Sep 18 '22 13:09

Alex.F