📱

Building Multiple Pages in Flutter

Aug 21, 2024

Flutter Multiple Page Application Tutorial

Introduction

  • Importance of multiple pages in Flutter applications.
  • Minimum pages in an app: Login page and Main page.
  • Overview of the application to be built: includes Login page, Main page, and Second page.

Application Flow

  • Login Page: Contains a login button.
    • Clicking the button redirects to the Main page.
  • Main Page: Contains a button that redirects to the Second page.
    • Clicking back does not return to the Login page; instead, it exits the app.
  • Second Page: Allows users to return to the Main page.

Concept of Pages in Flutter

  • Route: A page in Flutter.
  • Stack: Used to manage routes.
  • First page displayed is the Login page, added as the first layer in the stack.

Navigation Commands

  • Push Replacement: Replaces the current page (Login page) with another (Main page).
  • Push: Adds a new page (Second page) on top of the stack, allowing return to the previous page (Main page).
  • Pop: Removes the current page (Second page) from the stack.
  • Navigator: Manages the stack of routes.

Coding Walkthrough

  1. Create Project:
    • Start a new Flutter project.
    • Use Stateless widgets for static displays.
  2. Page Structure:
    • Create separate files for each page:
      • login_page.dart
      • main_page.dart
      • second_page.dart
  3. Login Page Implementation:
    • Create a Stateless widget named LoginPage.
    • Add a button labeled "LOGIN" (onPressed left empty for now).
  4. Main Page Implementation:
    • Create a Stateless widget named MainPage.
    • Add an AppBar with title "Main Page" and a button to go to Second Page.
  5. Second Page Implementation:
    • Create a Stateless widget named SecondPage.
    • Add a button to navigate back to the Main page.
  6. Modify main.dart:
    • Set home to LoginPage.
    • Implement navigation using Navigator methods:
      • For login button in LoginPage, use pushReplacement
      • For navigation to SecondPage, use push
      • For back navigation in SecondPage, use pop

Final Notes

  • Ensure to manage navigation properly to avoid returning to the Login page from Main page.
  • Application should function as expected:
    • Login button redirects to Main page.
    • Main page allows navigation to Second page.
    • Second page allows return to Main page.
    • Back from Main page exits the application.

Conclusion

  • The tutorial equips users with knowledge to create Flutter applications with multiple pages.
  • Encouragement to practice coding and explore Flutter capabilities.