11

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?

Hamed
  • 5,867
  • 4
  • 32
  • 56
kartheeki j
  • 2,206
  • 5
  • 27
  • 51

3 Answers3

21

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

drmirk
  • 403
  • 1
  • 7
  • 14
diegoveloper
  • 93,875
  • 20
  • 236
  • 194
2

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();
}
apaatsio
  • 3,073
  • 1
  • 22
  • 18
  • 1
    An explanation would have been great. – Ojonugwa Jude Ochalifu May 26 '20 at 05:57
  • 1
    @OjonugwaJudeOchalifu I can't remember exactly why I posted this or why one would prefer this solution over just using WillPopScope. It's almost exactly what WillPopScope does. Just look at https://github.com/flutter/flutter/blob/master/packages/flutter/lib/src/widgets/will_pop_scope.dart and also check the API docs for WillPopScope and ModalRoute for better understanding. – apaatsio May 27 '20 at 12:53
1

just set automaticallyImplyLeading: false,under appbar property