0
0
Fluttermobile~5 mins

Navigator.push and pop in Flutter

Choose your learning style9 modes available
Introduction

Navigator.push and pop help you move between screens in a mobile app. They let you open a new page and go back to the previous one easily.

When you want to open a new screen after a button tap.
When you want to go back to the previous screen after finishing a task.
When you want to show details of an item from a list on a new page.
When you want to create a flow of screens like a form or tutorial.
Syntax
Flutter
Navigator.push(context, MaterialPageRoute(builder: (context) => NewScreen()));

Navigator.pop(context);

Navigator.push adds a new screen on top of the current one.

Navigator.pop removes the top screen and goes back.

Examples
This opens SecondScreen on top of the current screen.
Flutter
Navigator.push(context, MaterialPageRoute(builder: (context) => SecondScreen()));
This closes the current screen and returns to the previous one.
Flutter
Navigator.pop(context);
This opens DetailScreen and passes data to it.
Flutter
Navigator.push(context, MaterialPageRoute(builder: (context) => DetailScreen(item: item)));
Sample App

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

Flutter
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: FirstScreen(),
    );
  }
}

class FirstScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('First Screen')),
      body: Center(
        child: ElevatedButton(
          child: Text('Go to Second Screen'),
          onPressed: () {
            Navigator.push(context, 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.pop(context);
          },
        ),
      ),
    );
  }
}
OutputSuccess
Important Notes

Always pass the current context to Navigator methods.

Use MaterialPageRoute to create a smooth transition between screens.

Navigator keeps a stack of screens; push adds, pop removes.

Summary

Navigator.push opens a new screen on top.

Navigator.pop closes the current screen and returns.

Use these to create smooth screen navigation in your app.