Home > Back-end >  How to replace 2 Navigator.pop with one method?
How to replace 2 Navigator.pop with one method?

Time:03-12

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);
                    }),

CodePudding user response:

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'),
        ),
      ),
    );
  }
}
  • Related