I am new to Flutter development. Can anyone share me how to disable the back press in flutter?
In Android, we can use onbackpressed method.
@Override
public void onBackPressed() {
// super.onBackPressed(); commented this line in order to disable back press
//Write your code here
Toast.makeText(getApplicationContext(), "Back press disabled!", Toast.LENGTH_SHORT).show();
}
In flutter how it possible to do?
To disable back button in Flutter, you can use the WillPopScope widget. The WillPopScope widget helps you get a callback whenever the back button is pressed. Inside the callback, if you return true the screen will be popped and if you return false, you have simply disabled the back button.
You need to pass null to onPressed parameter of Buttons in Flutter to disable.
Wrap your widget inside WillPopScope and return a false Future in the onWillPop property
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () => Future.value(false),
child: Scaffold(
appBar: AppBar(
title: const Text("Home Page"),
),
body: Center(
child: const Text("Home Page"),
),
),
);
}
Refer to this documentation: https://api.flutter.dev/flutter/widgets/WillPopScope-class.html
The easiest way is to use WillPopScope but here's an alternative method if for some reason you don't want to or can't use the WillPopScope widget.
class MyWidget extends StatefulWidget {
@override
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
ModalRoute<dynamic> _route;
@override
void didChangeDependencies() {
super.didChangeDependencies();
_route?.removeScopedWillPopCallback(_onWillPop);
_route = ModalRoute.of(context);
_route?.addScopedWillPopCallback(_onWillPop);
}
@override
void dispose() {
_route?.removeScopedWillPopCallback(_onWillPop);
super.dispose();
}
Future<bool> _onWillPop() => Future.value(false);
@override
Widget build(BuildContext context) => Container();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With