4

I have an app that I would like to try and remake in a flutter. In this app, the navigation routes change a lot and are not defined in a centralized place, but instead is defined by different developers in different "micro-projects" that are then bound together in the main app.

So my question is: Can I somehow dynamically set the routes on a MaterialApp at runtime? So that when a given widget class is loaded, it takes the MaterialApp instance and sets a new Map of routes on to the MaterialApp, and any routes that were before are now gone and replaced with new routes?

Enzokie
  • 7,365
  • 6
  • 33
  • 39
Neigaard
  • 3,726
  • 9
  • 49
  • 85
  • this question is in fact the same a duplicate of https://stackoverflow.com/questions/47419908/how-do-i-pass-non-string-data-to-a-named-route-in-flutter/47420619#47420619 The title is not exactly the same, but the answer is : dynamic routes – Rémi Rousselet Mar 02 '18 at 09:19

1 Answers1

3

There's a property on MaterialApp to handle dynamic routing : onGenerateRoute

For example if you do

onGenerateRoute: (routeSettings) {
 if (condition) {
   return new MaterialPageRoute(
     builder: (context) => new MyPage(),
     settings: routeSettings,
   );
 }
 // fallback route here
},

This will handle all routes even if they are not statically defined, as long as they match condition

But remember that Flutter forbid the usage of dart:mirror. Which means that if you want to push things further you'd have to use a code generator. Combined to a decorator, you can make that whenever you write :

class MyWidget extends StatelessWidget {
  final int prop;

  @MyNavigation
  MyWidget({this.prop});

  @override
  Widget build(BuildContext context) {
    return new Container();
  }
}

it will automatically generate the code to handle the route /mywidget/{prop}.

Rémi Rousselet
  • 256,336
  • 79
  • 519
  • 432
  • I'm trying to put my routes into a static route table and am struggling with the syntax. The documentation on anything with flutter that's not in a tutorial is god awful imo. How do you get a WidgetBuilder from a widget? – TemporaryFix Dec 28 '18 at 22:43