flutter remove back button on appbar
You can remove the back button by passing an empty new Container()
as the leading
argument to your AppBar
.
If you find yourself doing this, you probably don't want the user to be able to press the device's back button to get back to the earlier route. Instead of calling pushNamed
, try calling Navigator.pushReplacementNamed
to cause the earlier route to disappear.
The function pushReplacementNamed
will remove the previous route in the backstack and replace it with the new route.
Full code sample for the latter is below.
import 'package:flutter/material.dart';
class LogoutPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("Logout Page"),
),
body: new Center(
child: new Text('You have been logged out'),
),
);
}
}
class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("Remove Back Button"),
),
floatingActionButton: new FloatingActionButton(
child: new Icon(Icons.fullscreen_exit),
onPressed: () {
Navigator.pushReplacementNamed(context, "/logout");
},
),
);
}
}
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
home: new MyHomePage(),
routes: {
"/logout": (_) => new LogoutPage(),
},
);
}
}
I believe the solutions are the following
You actually either:
Don't want to display that ugly back button ( :] ), and thus go for :
AppBar(...,automaticallyImplyLeading: false,...)
;Don't want the user to go back - replacing current view - and thus go for:
Navigator.pushReplacementNamed(## your routename here ##)
;Don't want the user to go back - replacing a certain view back in the stack - and thus use:
Navigator.pushNamedAndRemoveUntil(## your routename here ##, f(Route<dynamic>)→bool);
where f is a function returningtrue
when meeting the last view you want to keep in the stack (right before the new one);Don't want the user to go back - EVER - emptying completely the navigator stack with:
Navigator.pushNamedAndRemoveUntil(context, ## your routename here ##, (_) => false);
Cheers
A simple way to remove the back button in the AppBar is to set automaticallyImplyLeading
to false
.
appBar: AppBar(
title: Text("App Bar without Back Button"),
automaticallyImplyLeading: false,
),