flutter: How to not exit the app on back button press

Viewed 2832

The usual behaviour for the app is to exit, when back button is pressed. What I want is for the app to go to background without exiting, when back button is pressed. Just like what happens when we switch from one app to another.

I know that it will involve using WillPopScope() but how to handle the onBackPressed event to keep the app in background, and not exit the same.

2 Answers

Though it is pretty late to answer, but I hope it may help others as well as myself.

There's a plugin that can help in this case I think.

https://pub.dev/packages/move_to_background

It's easy to use, and has a pretty high rating.

Try the following code it will work:

Code:

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

void main() => runApp((MainScreen()));

class MainScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: MyApp(),
    );
  }
}

class MyApp extends StatefulWidget {
  MyApp({Key key}) : super(key: key);

  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () => SystemChannels.platform.invokeMethod(
          'SystemNavigator.pop'), // this is use to keep the app in background
      child: Scaffold(
        body: Center(
          child: Text("Text"),
        ),
      ),
    );
  }
}
Related