Basic navigation by using 'Navigator.push' & 'Navigator.pop()', for example, we have two screen, screen1 and screen2, we want to navigate between two screens:
// Screen1.dart import 'package:flutter/material.dart'; import 'screen2.dart'; class Screen1 extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Colors.red, title: Text('Screen 1'), ), body: Center( child: RaisedButton( color: Colors.red, child: Text('Go Forwards To Screen 2'), onPressed: () { Navigator.push( context, MaterialPageRoute(builder: (context) { return Screen2(); }), ); }, ), ), ); } }
Screen2.dart:
import 'package:flutter/material.dart'; class Screen2 extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Colors.blue, title: Text('Screen 2'), ), body: Center( child: RaisedButton( color: Colors.blue, child: Text('Go Back To Screen 1'), onPressed: () { Navigator.pop(context); }, ), ), ); } }
Using the named route:
In main.dart, we can list all the routes:
class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( // home: Screen0(), initialRoute: '/', routes: { '/': (context) => Screen0(), '/first': (context) => Screen1(), '/second': (context) => Screen2() }, ); } }
To be noticed: 'home' & 'initialRoute' cannot be used at the same time.
child: Column( children: <Widget>[ RaisedButton( color: Colors.red, child: Text('Go To Screen 1'), onPressed: () { Navigator.pushNamed(context, '/first'); }, ), RaisedButton( color: Colors.blue, child: Text('Go To Screen 2'), onPressed: () { Navigator.pushNamed(context, '/second'); }, ), ], ),