how to disable phone back press in flutter

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();
}

Tags:

Dart

Flutter