In Flutter, a screen (page, route) is a normal widget but it’s loaded such that it fills the entire (or the majority) of the device screen. To navigate from one screen to another, we can use Navigator.push(). To go back, we use Navigator.pop().
Example
Preview
We’ll build a tiny Flutter app that has only 2 screens: HomeScreen() and SettingScreen(). Each screen is simple and just contains a button and an AppBar.
The Code
Navigate from the Home screen to the Setting screen:
Navigator.push(
context,
MaterialPageRoute(builder: (_) => const SettingScreen())
);
Go back to the Home screen from the Setting screen:
Navigator.of(context).pop();
Complete code in main.dart:
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const MaterialApp(
// hide the debug banner
debugShowCheckedModeBanner: false,
title: "Kindacode.com",
home: HomeScreen(),
);
}
}
// Home Screen
class HomeScreen extends StatelessWidget {
const HomeScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Home'),
),
body: Center(
child: ElevatedButton(
child: const Text('Go To Setting Screen'),
// Navigate to the Setting screen
onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (_) => const SettingScreen()));
},
)));
}
}
// Setting Screen
class SettingScreen extends StatelessWidget {
const SettingScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Setting'),
),
body: Center(
child: TextButton(
child: const Text('Go Back'),
// Go back to the Home screen
onPressed: () {
Navigator.of(context).pop();
},
),
),
);
}
}
Hope this helps. Further reading:
- Using GetX (Get) for Navigation and Routing in Flutter
- How to get the Current Route Name in Flutter
- Flutter: Customize the Android System Navigation Bar
- Example of CupertinoSliverNavigationBar in Flutter
- Flutter: Drawer Navigation example
- Using Chip widget in Flutter: Tutorial & Examples
You can also check out our Flutter category page or Dart category page for the latest tutorials and examples.