0
0
Fluttermobile~5 mins

Why navigation manages screen transitions in Flutter

Choose your learning style9 modes available
Introduction

Navigation helps move between different screens in an app smoothly. It keeps track of where you are and where you want to go next.

When you want to open a new screen after a button tap.
When you need to go back to the previous screen.
When switching between different sections of an app.
When showing details from a list on a new page.
When closing a screen and returning data to the previous one.
Syntax
Flutter
Navigator.of(context).push(MaterialPageRoute(builder: (context) => NewScreen()));
Navigator.of(context).pop();
Use Navigator.of(context).push to go to a new screen.
Use Navigator.of(context).pop to go back to the previous screen.
Examples
This code moves from the current screen to a DetailScreen.
Flutter
Navigator.of(context).push(MaterialPageRoute(builder: (context) => DetailScreen()));
This code goes back to the previous screen.
Flutter
Navigator.of(context).pop();
Sample App

This app has two screens. The first screen has a button to go to the second screen. The second screen has a button to go back.

Flutter
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(
          child: Text('Go to Second Screen'),
          onPressed: () {
            Navigator.of(context).push(
              MaterialPageRoute(builder: (context) => SecondScreen()),
            );
          },
        ),
      ),
    );
  }
}

class SecondScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Second Screen')),
      body: Center(
        child: ElevatedButton(
          child: Text('Go Back'),
          onPressed: () {
            Navigator.of(context).pop();
          },
        ),
      ),
    );
  }
}
OutputSuccess
Important Notes

Navigation keeps a stack of screens, like a stack of cards.

Push adds a new screen on top; pop removes the top screen.

This helps users move forward and backward easily.

Summary

Navigation controls moving between screens in an app.

Use Navigator.of(context).push to open a new screen.

Use Navigator.of(context).pop to go back to the previous screen.