flutter disable back button

There may be some pages where you want to disable back button in flutter app. In this Flutter article let’s checkout how to disable back button in flutter.

So, To disable back button in flutter, we can make use of Flutter WillPopScope Widget and within the widget we can use onWillPop property that will simply return false like shown below:

WillPopScope(
      onWillPop: () async {
        /* Do something here if you want */
        return false;
      },
      child: Scaffold(
          /* ... */
          ),
  );

The Complete Code to Disable Back Button press in flutter

// main.dart
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        // Remove the debug banner
        debugShowCheckedModeBanner: false,
        title: 'Sample App',
        theme: ThemeData(
          primarySwatch: Colors.amber,
        ),
        home: const HomePage());
  }
}

// Home Page
class HomePage extends StatelessWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: const Text('ProtoCodersPoint.com'),
      ),
      body: Center(
        child: ElevatedButton(
          child: const Text('Go to OtherPage'),
          onPressed: () {
            Navigator.of(context).push(
                MaterialPageRoute(builder: (context) => const OtherPage()));
          },
        ),
      ),
    );
  }
}

// Other Page
class OtherPage extends StatelessWidget {
  const OtherPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        // show the snackbar with some text
        ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
            content: Text('The System Back Button is Deactivated')));
        return false;
      },
      child: Scaffold(
        appBar: AppBar(
          automaticallyImplyLeading: false,
          centerTitle: true,
          title: const Text('Other Page'),
        ),
        body: const Padding(
          padding: EdgeInsets.all(30),
          child: Text(
            'Are you looking for a way to go back? Hmm...',
            style: TextStyle(fontSize: 24),
          ),
        ),
      ),
    );
  }
}

The above code will prevent our app getting closed when user press back button, so we have simple disabled back button in flutter by using WillPopScope widget.