What is the best Practice for assigning routeNames in Flutter?

Viewed 383

Coming from Django, the way Flutter recommends for setting routenames, (e.g https://flutter.dev/docs/cookbook/navigation/named-routes) like "/main", starting with / and not ending with / looks a bit weird to me. As long as all route names start with / and end without /, it is possible to have the same logic as django, being able to add one path to the other without problems.

So, I'm curiuos:

Are there down-sides of using routenames the django ('/', 'main/', 'main/deeper/') way in Flutter?

What is the current best practice?

Which naming style do you prefer and why?

1 Answers

I advise you to assign a constant static id to each class containing a view, in this way you can call it wherever you want with Navigator.of(context).pushNamed(MyHomePage.id), being able to modify it in one place.

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      initialRoute: MyHomePage.id,
      routes: {
        MyHomePage.id : (context) => MyHomePage(),
        // other routes
      },
    );
  }
}

class MyHomePage extends StatefulWidget {
  static const String id = "homeScreen"; // Change this
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}
Related