DEV Community

loading...
Cover image for Pro Flutter Navigation

Pro Flutter Navigation

prakashselvaraj profile image Prakash S ・2 min read

Navigation from one page to other is vital part in mobile app development.
Flutter comes with very easy solutions for navigation using πŸ₯°NavigatorπŸ₯° class.

In this post I am going to cover two types of navigation in flutter.

1) Simple navigation
2) Named navigation

Our scenario is to move to the second page on button pressed, we were taking two pages
1) Home page
2) Second page

also we are passing a string to second page.

Simple navigation

Simple navigation can be achieved by using Navigator push method

the syntax for Navigator push is
'Navigator.push(context, MaterialPageRoute(builder: (context) => Widget()));'

Seems simple isnt it, See below for code snippet.

Named navigation

I would say this is the best way to handle navigation, you will find the answer soooon πŸ˜‰

Named navigation is using routing concept, now you get it why it is the best way ahhh πŸ˜‡

All the navigation routes are isolated/dedicated in one place, so we don't need to worry about instantiating class in our dart code.

lets jump into the code.

Flutter Material app comes with function callback for generating the App routes

onGenerateRoute

We can define our routes in a function and set it to onGenerateRoute, so that flutter knows where to go on navigation.

Syntax for named routing using navigator:
Navigator.of(context).pushNamed('/route', arguments: args);

even simple isn't it??

See below code snippet

for full sample please find in the Github repo link

Happy fluterring πŸ˜‡πŸ˜‡!!

Discussion (2)

pic
Editor guide
Collapse
renodesper profile image
Boy Sandy G. A.

Hi @prakashselvaraj , care to give an example for named route when we want to send multiple arguments? I haven't found a good way to receive it on the destination screen.

For example, this is the destination screen constructor:

  ResultPage({
    @required this.bmiResult,
    @required this.resultText,
    @required this.interpretation,
  }

And this is the arguments:

..., arguments: <String, String>{'bmiResult': 1, 'resultText': 'x', 'interpretation': 'y'});
Collapse
prakashselvaraj profile image
Prakash S Author

Navigator pushNamed accepts only one argument which is an Object type, So you can pass the desired argument as class/list or whatever object type which match your requirement.

Passing Data
Getting Data

also in your case

<String, String>{'bmiResult': '1', 'resultText': 'x', 'interpretation': 'y'}

you can use Map on the navigating page

MapDataArgument

Hope this answers you !!

Happy fluterring πŸ˜‡πŸ˜‡!!