Navigation is done is Flutter using the Navigator class.
Lets look at a simple example
The first thing you have to register routes for difference screen is to build a Map of ‘String’ (route) and the page (Widget).
Lets say I have a utility class for the Creating Routes named routes.dart. The contents of route.dart contains the below code
import 'package:flutter/material.dart'; import 'exercises_screen.dart'; class Routes { static Map<String, WidgetBuilder> buildRoutes() { Map<String, WidgetBuilder> routes = new Map<String, WidgetBuilder>(); routes.putIfAbsent( '/exercises', () => (BuildContext context) => new Exercises()); return routes; } }
My Exercises class will simply look like this
import 'package:flutter/material.dart'; class Exercises extends StatefulWidget { const Exercises({Key key}) : super(key: key); static const String routeName = '/exercises'; @override State<StatefulWidget> createState() { return new _ExercisesState(); } } class _ExercisesState extends State<Exercises> { @override Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar(title: new Text("Exercises")), body: new Container(child: Text("Exercises")), ); } }
Register the Routes
Note the buildRoutes() function used in the “routes” property of the initial MaterialApp.
import 'package:flutter/material.dart'; import 'home.dart'; import 'routes.dart'; void main() => runApp(new MyApp()); class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return new MaterialApp( title: 'Flutter Demo', theme: new ThemeData( primarySwatch: Colors.blue, ), home: new MyHomePage(title: 'Home'), routes: Routes.buildRoutes(), // register the routes for the application. ); } }
Invoke the Push
Its Simple as that…
Navigator.pushNamed(context, '/exercises');
Note: This will only work if you have registered the screen “Exercises” with route “/exercises”.
Pop Screen
To Pop current screen
Navigator.of(context).pop();
home.dart file code, not hare please full source code