Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to disable phone back press in flutter

Tags:

flutter

dart

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?

like image 254
kartheeki j Avatar asked Aug 14 '18 05:08

kartheeki j


People also ask

How do I turn off back press in Flutter?

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.

How do I turn off the home button Flutter?

You need to pass null to onPressed parameter of Buttons in Flutter to disable.


2 Answers

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

like image 102
diegoveloper Avatar answered Oct 13 '22 07:10

diegoveloper


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();
}
like image 38
apaatsio Avatar answered Oct 13 '22 08:10

apaatsio