When you close a flutter app via the back button on Android, there are some problems concerning plugins. The dart/flutter side of the plugin gets restarted, the android part not. This causes trouble, especially with background activities like playing audio. I think it is a critical issue so I created a GitHub issue: https://github.com/flutter/flutter/issues/31734

I want to do a workaround, so if the app gets closed via the back button, the playback should get stopped.

I tried to detect the back button close action via the didChangeAppLifecycleState method. But there I can determine if it is a normal close action or with the back button.

You can try this yourself with the example of the audioplayers plugin. I also created there a new issue

Answer

It seems to me that you cannot precisely determine whether an app has been closed via the back button. Instead, you can determine if an app is going to be closed via the back button using the back_button_interceptor as an intermediate:

bool myInterceptor(bool stopDefaultButtonEvent) {
  String currentRoute = BackButtonInterceptor.getCurrentNavigatorRouteName(context);

  if (currentRoute == '/home') {
    // Back button has been pressed while you're in the home, so the app is going to close
    doYourStuff();
  }

  return false;
}

Of course you have to implement routes to make this happen, but that is the most precise approach I could find, since everything that creates an overlay (and so overrides back button action) changes the result of getCurrentNavigatorRouteName, including dialogs and even PopupMenus from AppBar.

  • 1
Reply Report

Warm tip !!!

This article is reproduced from Stack Exchange / Stack Overflow, please click

Trending Tags

Related Questions