Navigate between Screens in Flutter
TL;DR
In Flutter, screens and pages are usually called routes.
Navigate to Another Screen
Use Navigator.push
along with MaterialPageRoute
:
Navigator.push(context, MaterialPageRoute(builder: (context) => AnotherScreen()));
Using Sprinkle library
context.display(AnotherScreen())
Navigate Back
Use Navigator.pop
Navigator.pop(context);
Using Sprinkle library
context.back()
Full Code Example
import 'package:flutter/material.dart';
void main() => runApp(App());
class App extends StatelessWidget {
@override
Widget build(context) {
return MaterialApp(
title: 'Flutter Navigation',
home: MainScreen(),
);
}
}
class MainScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Main Screen'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RaisedButton(
textColor: Colors.white,
color: Colors.blue,
child: Text('Navigate to Another Screen'),
onPressed: () {
Navigator.push(context, MaterialPageRoute(builder: (context) => AnotherScreen()));
},
)
],
),
),
);
}
}
class AnotherScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Sub Page'),
backgroundColor: Colors.redAccent,
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RaisedButton(
textColor: Colors.white,
color: Colors.redAccent,
child: Text('Navigate back to Main Screen'),
onPressed: () {
Navigator.pop(context);
},
)
],
),
),
);
}
}