In this example, we will show you how to clear the navigation history stacks of routes and screen pages in Flutter. You may need to clear the navigation history in some cases like pages after splash screen, login screen, or similar kinds of pages where you want to disable the back button. See the example:
Navigator.pushAndRemoveUntil(context, MaterialPageRoute(builder: (BuildContext context){
return NewPage();
}), (r){
return false;
});
See this also: How to Disable Back Button in Flutter
Navigator.pushReplacement(context, MaterialPageRoute(builder: (BuildContext context){
return NewPage();
}));
This code will navigate to the new page, and replace the history stack with the current stack.
import 'package:flutter/material.dart';
void main(){
runApp(MyApp());
}
class MyApp extends StatelessWidget{
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Home(),
);
}
}
class Home extends StatefulWidget{
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Clear Navigation History"),
backgroundColor: Colors.orangeAccent
),
body: Container(
padding: EdgeInsets.only(top:20, left:20, right:20),
alignment: Alignment.topCenter,
child: Column(
children: [
ElevatedButton(
onPressed: (){
Navigator.pushReplacement(context, MaterialPageRoute(builder: (BuildContext context){
return NewPage();
}));
},
child: Text("Go to Next Page and Clear Current History")
),
ElevatedButton(
onPressed: (){
Navigator.pushAndRemoveUntil(context, MaterialPageRoute(builder: (BuildContext context){
return NewPage();
}), (r){
return false;
});
},
child: Text("Go to Next Page and Clear All History")
)
],)
)
);
}
}
class NewPage extends StatelessWidget{
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Next Page")),
body: Container(
),
);
}
}
In this way, you can clear navigation history stacks in Flutter.
Please Wait...
No any Comments on this Article