Flutter Navigator
Navigation is how users move between screens in a Flutter app. The Navigator class manages a stack of routes, and you push or pop screens onto that stack. Think of it like a deck of cards — you add a new card on top when you navigate forward, and remove it when you go back.
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomeScreen(),
);
}
}
class HomeScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Home')),
body: Center(
child: ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => DetailScreen()),
);
},
child: Text('Go to Detail'),
),
),
);
}
}
class DetailScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Detail')),
body: Center(
child: ElevatedButton(
onPressed: () {
Navigator.pop(context);
},
child: Text('Go Back'),
),
),
);
}
}
Try it Yourself ->
Navigator.push and Navigator.pop
Navigator.push adds a new route to the top of the stack. You provide the current context and a MaterialPageRoute, which tells Flutter which widget to display on the new screen. Navigator.pop removes the top route, revealing the previous screen underneath.
// Push a new screen
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondScreen()),
);
// Pop back to the previous screen
Navigator.pop(context);
Try it Yourself ->
Passing Data via Constructor
You can pass data to a new screen by adding constructor parameters to your widget. This is the simplest way to share information between screens without any fancy routing setup.
class DetailScreen extends StatelessWidget {
final String message;
DetailScreen({required this.message});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Detail')),
body: Center(
child: Text(message, style: TextStyle(fontSize: 24)),
),
);
}
}
// When pushing:
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DetailScreen(message: 'Hello from Home!'),
),
);
Try it Yourself ->