假設我Navigator.pop(context)連續使用 2 次關閉 AlerDialog 并關閉頁面。是否可以用一個功能替換這兩種方法?如果是這樣,怎么做?
ElevatedButton(
child: const Text('Do not save'),
onPressed: () {
Navigator.pop(context);
Navigator.pop(context);
}),
uj5u.com熱心網友回復:
一種方法是使用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'),
),
),
);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/440734.html
上一篇:如何使用FirestoreFlutter對串列進行排序?
下一篇:如何洗掉我在螢屏截圖中標記的內容
