DEV Community

Cover image for Pro Flutter Navigation
Prakash S
Prakash S

Posted on

2 1

Pro Flutter Navigation

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

void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Navigation Demo',
theme: ThemeData(primarySwatch: Colors.deepOrange),
home:HomePage()
);
}
}

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

Seems simple isnt it, See below for code snippet.

class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('I am home page :)'),
),
body: Center(
child: RaisedButton(
child: Text('Go to Second'),
onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => SecondPage('from first page')));
},
),
));
}
}
class SecondPage extends StatelessWidget {
final String data;
SecondPage(this.data);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('I am second page :)'),
),
body: Center(
child: Text('I am second page ${this.data}'),
),
);
}
}

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.

class RouteCatalog {
static Route<dynamic> generateRoute(RouteSettings settings) {
final arguments = settings.arguments;
switch (settings.name) {
case '/':
return MaterialPageRoute(builder: (_) => HomePage());
case '/second':
return MaterialPageRoute(builder: (_) => SecondPage(data: arguments));
default:
return MaterialPageRoute(builder: (_) => OOPSPage());
}
}
}

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

even simple isn't it??

See below code snippet

//App class
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Navigation Demo',
theme: ThemeData(primarySwatch: Colors.deepOrange),
initialRoute: '/',
onGenerateRoute: RouteCatalog.generateRoute,
);
}
}
// Home page
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Home'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('HomePage', style: TextStyle(fontSize: 20),),
RaisedButton(
child: Text('GO TO NextPage'),
onPressed: () {
Navigator.of(context)
.pushNamed('/second', arguments: 'from home');
},
)
],
),
),
);
}
}
// Second page
class SecondPage extends StatelessWidget {
final String data;
SecondPage({@required this.data});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Second Page'),
),
body: Container(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[Text('Second Page', style: TextStyle(fontSize: 30),), Text(this.data)],
),
),
),
);
}
}

for full sample please find in the Github repo link

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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here β†’

Top comments (2)

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,
  }
Enter fullscreen mode Exit fullscreen mode

And this is the arguments:

..., arguments: <String, String>{'bmiResult': 1, 'resultText': 'x', 'interpretation': 'y'});
Enter fullscreen mode Exit fullscreen mode
Collapse
 
prakashselvaraj profile image
Prakash S β€’

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 πŸ˜‡πŸ˜‡!!

Sentry mobile image

Improving mobile performance, from slow screens to app start time

Based on our experience working with thousands of mobile developer teams, we developed a mobile monitoring maturity curve.

Read more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay