Skip to content

Instantly share code, notes, and snippets.

@SuperPenguin
Created June 24, 2022 07:02
Show Gist options
  • Save SuperPenguin/645c49a578f873705a588fca4190175f to your computer and use it in GitHub Desktop.
Save SuperPenguin/645c49a578f873705a588fca4190175f to your computer and use it in GitHub Desktop.
Navigator.pushAndRemoveUntil
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
brightness: Brightness.light,
),
home: const PageA(),
);
}
}
class PageA extends StatefulWidget {
const PageA({Key? key}) : super(key: key);
@override
State<PageA> createState() => _PageAState();
}
class _PageAState extends State<PageA> {
@override
void initState() {
super.initState();
print('Init A');
}
@override
void dispose() {
print('Dispose A');
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Page A'),
),
body: Center(
child: ElevatedButton(
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => const PageB(),
),
);
},
child: const Text('Push B'),
),
),
);
}
}
class PageB extends StatefulWidget {
const PageB({Key? key}) : super(key: key);
@override
State<PageB> createState() => _PageBState();
}
class _PageBState extends State<PageB> {
@override
void initState() {
super.initState();
print('Init B');
}
@override
void dispose() {
print('Dispose B');
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Page B'),
),
body: Center(
child: ElevatedButton(
onPressed: () {
Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(
builder: (context) => const PageC(),
),
(route) => false,
);
},
child: const Text('Push and Remove until C'),
),
),
);
}
}
class PageC extends StatefulWidget {
const PageC({Key? key}) : super(key: key);
@override
State<PageC> createState() => _PageCState();
}
class _PageCState extends State<PageC> {
@override
void initState() {
super.initState();
print('Init C');
}
@override
void dispose() {
print('Dispose C');
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Page C'),
),
body: const SizedBox(),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment