How to replace 2 Navigator.pop with one method?

Issue

Say I use Navigator.pop(context) 2 times in a row to close the AlerDialog and close the page. Is it possible to replace these 2 methods with one function? If so, how?

ElevatedButton(
                    child: const Text('Do not save'),
                    onPressed: () {
                      Navigator.pop(context);
                      Navigator.pop(context);
                    }),

Solution

One way is to use Navigator.popUntil

Here’s an example of using it to pop all the way to the first route:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}): super(key: key);

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  const HomePage({Key? key}): super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Home Page'),
      ),
      body: Center(
        child: TextButton(
          onPressed: () {
            Navigator.of(context).push<void>(
              MaterialPageRoute(builder: (context) => const SecondPage()),
            );
          },
          child: const Text('Second Page'),
        ),
      ),
    );
  }
}

class SecondPage extends StatelessWidget {
  const SecondPage({Key? key}): super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Second Page'),
      ),
      body: Center(
        child: TextButton(
          onPressed: () {
            showDialog<void>(
              context: context,
              builder: (context) {
                return Dialog(
                  child: Center(
                    child: TextButton(
                      onPressed: () {
                        Navigator.of(context).popUntil((route) => route.isFirst);
                      },
                      child: const Text('Back Home'),
                    ),
                  ),
                );
              }
            );
          },
          child: const Text('Open Dialog'),
        ),
      ),
    );
  }
}

Answered By – Will Hlas

Answer Checked By – Willingham (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.