import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Navigation Demo',
home: const WelcomePage(),
);
}
}
class WelcomePage extends StatelessWidget {
const WelcomePage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Welcome Page')),
body: Center(
child: ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const SecondPage()),
);
},
child: const Text('Go to Page 2'),
),
),
);
}
}
class SecondPage extends StatelessWidget {
const SecondPage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Second Page')),
body: Center(
child: ElevatedButton(
onPressed: () {
Navigator.pop(context);
},
child: const Text('Back to Page 1'),
),
),
);
}
}
This app has two pages: WelcomePage and SecondPage.
On WelcomePage, the button uses Navigator.push to move to SecondPage. This adds the new page on top of the navigation stack, showing the new screen.
On SecondPage, the button uses Navigator.pop to go back. This removes the current page from the stack, returning to the previous screen.
This shows how Flutter's Navigator manages screen transitions by stacking pages and moving between them.