Icon
Get In Touch
#flutter

Navigating Between Screens

In Flutter, navigation is managed using a stack of routes. This section explains how to switch between screens, pass data between routes, and manage named routes.

Navigator and Routing

- Navigator.push(): Pushes a new route onto the stack (opens a new screen).
- Navigator.pop(): Pops the current route off the stack (goes back to the previous screen).

1
import 'package:flutter/material.dart';
2
3
void main() {
4
runApp(const MainApp());
5
}
6
7
class MainApp extends StatelessWidget {
8
const MainApp({super.key});
9
10
@override
11
Widget build(BuildContext context) {
12
return MaterialApp(
13
debugShowCheckedModeBanner: false,
14
initialRoute: '/',
15
routes: {
16
'/': (context) => const HomePage(),
17
'/second': (context) => const SecondPage(),
18
},
19
);
20
}
21
}
22
23
// Home screen
24
class HomePage extends StatelessWidget {
25
const HomePage({super.key});
26
27
@override
28
Widget build(BuildContext context) {
29
return Scaffold(
30
appBar: AppBar(title: const Text('Home Page')),
31
body: Center(
32
child: ElevatedButton(
33
onPressed: () {
34
Navigator.pushNamed(context, '/second'); // Navigating to SecondPage
35
},
36
child: const Text('Go to Second Page'),
37
),
38
),
39
);
40
}
41
}
42
43
// Second screen
44
class SecondPage extends StatelessWidget {
45
const SecondPage({super.key});
46
47
@override
48
Widget build(BuildContext context) {
49
return Scaffold(
50
appBar: AppBar(title: const Text('Second Page')),
51
body: const Center(
52
child: Text('Welcome to the second page!'),
53
),
54
);
55
}
56
}

Key Takeaways

- Use Navigator.push() to transition to a new screen.
- Named routes allow for better route management in large apps.

©2024 Codeblockz

Privacy Policy