free geoip
50

Using Navigator.push and pop in Flutter

Navigating between screens in a Flutter app is essential for managing user interaction and flow. This tutorial will guide you…

Navigating between screens in a Flutter app is essential for managing user interaction and flow. This tutorial will guide you through how to use Navigator.push and Navigator.pop in Flutter using Android Studio, enabling you to switch between different pages efficiently. We will implement two screens: a HomePage and a SecondPage, with clear examples of how to navigate forward and back between them.

Using Navigator.push and pop in Flutter

You’ll also understand how to pass data between pages using constructors and receive results back when popping. This approach is critical when you build multi-page apps like forms, detail views, or wizards.

External Reference: Learn more about navigation on Flutter’s official documentation.

Step-by-Step Code Example

main.dart

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Navigation Demo',
      home: HomePage(),
    );
  }
}

home_page.dart

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

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Home Page')),
      body: Center(
        child: ElevatedButton(
          onPressed: () async {
            final result = await Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => SecondPage(data: 'Hello from HomePage'),
              ),
            );
            ScaffoldMessenger.of(context)
              .showSnackBar(SnackBar(content: Text('Returned: $result')));
          },
          child: Text('Go to Second Page'),
        ),
      ),
    );
  }
}

second_page.dart

import 'package:flutter/material.dart';

class SecondPage extends StatelessWidget {
  final String data;

  SecondPage({required this.data});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Second Page')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('Received: $data'),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                Navigator.pop(context, 'Data from SecondPage');
              },
              child: Text('Go Back with Data'),
            ),
          ],
        ),
      ),
    );
  }
}

rysasahrial

Leave a Reply

Your email address will not be published. Required fields are marked *