#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).
1import 'package:flutter/material.dart';23void main() {4runApp(const MainApp());5}67class MainApp extends StatelessWidget {8const MainApp({super.key});910@override11Widget build(BuildContext context) {12return MaterialApp(13debugShowCheckedModeBanner: false,14initialRoute: '/',15routes: {16'/': (context) => const HomePage(),17'/second': (context) => const SecondPage(),18},19);20}21}2223// Home screen24class HomePage extends StatelessWidget {25const HomePage({super.key});2627@override28Widget build(BuildContext context) {29return Scaffold(30appBar: AppBar(title: const Text('Home Page')),31body: Center(32child: ElevatedButton(33onPressed: () {34Navigator.pushNamed(context, '/second'); // Navigating to SecondPage35},36child: const Text('Go to Second Page'),37),38),39);40}41}4243// Second screen44class SecondPage extends StatelessWidget {45const SecondPage({super.key});4647@override48Widget build(BuildContext context) {49return Scaffold(50appBar: AppBar(title: const Text('Second Page')),51body: const Center(52child: 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