如何用一种方法替换2 Navigator.pop?

How to replace 2 Navigator.pop with one method?

假设我连续使用Navigator.pop(context) 2 次来关闭AlerDialog 并关闭页面。是否可以用一个功能替换这两种方法?如果是,怎么做?

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

一种方法是使用 Navigator.popUntil

下面是一个使用它一直弹出到第一个路由的例子:

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