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



假设我连续使用Navigator.pop(context)两次来关闭AlertDialog并关闭页面。是否可以用一个函数替换这两种方法?如果是,如何?

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

最新更新