import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() {
    return _MyHomePageState();
  }
}

class _MyHomePageState extends State<MyHomePage> with WidgetsBindingObserver {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    print(state);
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        //do something here before pop
        return true;
      },
      child: Scaffold(
        body: Container(),
      ),
    );
  }
}

My app is above. I am trying to detect when my app is killed on Android with overview button and by closing the app by swiping. The problem is AppLifeCycleState.detached is never passed to my callback. If I close the app by pressing back button on root, it is printed. If I kill it with swiping from overview button the callback is not there. I am essentially trying to get the onDestroy() call of native android.

Here is the log I get:

D/SurfaceView(24406): windowStopped(true) false io.flutter.embedding.android.FlutterSurfaceView{d98238 V.E...... ........ 0,0-1080,2154} of [email protected][MainActivity]
I/flutter (24406): AppLifecycleState.paused
Lost connection to device.

ExpectedLog:

D/SurfaceView(25394): windowStopped(true) false io.flutter.embedding.android.FlutterSurfaceView{2d5a56d V.E...... ........ 0,0-1080,2154} of [email protected][MainActivity]
I/flutter (25394): AppLifecycleState.paused
I/flutter (25394): AppLifecycleState.detached
Lost connection to device.


Solution 1: cs guy

Apparently, this is an ongoing bug with flutter. https://github.com/flutter/flutter/issues/57594