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 ); } }
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.
//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"
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With