Router



Introduction

Routes helps us navigate users around our apps. They provide a simple journey usually from the (/) index page. You can add routes in Nylo with the lib/routers/router.dart file. In this file, you’ll be able to assign the name of the route e.g. “/settings” and also the widget view you want to show.

You may also need to pass data from one view to the other and that’s also possible when navigating from a widget. We’ll dive deeper into how all this works in Nylo.

Nylo uses the Sailor Flutter package to manage this under the hood of Nylo, you can check out that library too for more information.


Adding routes

This is the most basic form of adding a new route to your project.

router.addRoute(NyRoute(
  name: "/settings-page",
  view: (context) => SettingsPage(),
));

You can also add multiple routes at once too.

router.addRoutes([
NyRoute(
  name: "/settings-page",
  view: (context) => SettingsPage(),
),

NyRoute(
  name: "/profile-page",
  view: (context) => ProfilePage(),
),
]);

Inside the router.dart file you'll find the buildRouter function, this is called when initializing the app. All your routes should live within this file to help keep things organized.

{info} To add a route you just need to call a method on the router variable passed into the nyCreateRoutes method.

Once you add your NyRoute instance to the addRoute parameter you'll be able to add your name for the route path i.e "/about-us" and then set up the view parameter which is used for returning your Page/Widget.


Navigating to pages

To start navigating to other pages, you can use the NyNav class. This will push the new page to the top of the navigation stack.

void onPressedSettings() {
    NyNav.to(routeName: "/settings-page");
}

Once you're on the new page, you can also call Navigator.of(context).pop() to go back to the existing Page.


Passing data to routes

You may sometimes need to pass data from one screen to another. Here’s a simple example of how that might look in Nylo.

// HOME PAGE
void onPressedSettings() {
  User user = new User();
  user.firstName = 'Anthony';

    NyNav.to(routeName: "/settings-page", data: user);
}

...

Next on our other page

...
class _ProfilePageState extends State<ProfilePage> {
  @override
  void initState() {
    super.initState();

  print(widget.controller.request.data().toString());

  }

If we take a closer look for how this works you’ll notice that we are accessing data() from a request variable on the controller.

For this to work your page will need to extend the StatefulPageWidget class and have a controller.