Search code examples
flutterbackground-processaudio-player

Run function when app is in background | Flutter


My app contains some background music. I want to be able to shut this off when the user leaves the app. I can do this partially by using WillPopScope:

Future<bool> _willPopCallback() async {
    player.stop();
    return true;
  }

But the reason this isn't the right thing is that it only works when the user clicks on the back-button, not the home-button. And that's quite a problem, because then the music will keep playing in the background. How do I fix this?


Solution

  • Use WidgetsBindingObserver which provides Widget callback when its getting paused/resumed. This can solve your problem

    class MusicWidget extends StatefulWidget {
      @override
      _MusicWidgetState createState() => _MusicWidgetState();
    }
    
    class _MusicWidgetState extends State<MusicWidget> with WidgetsBindingObserver {
      @override
      void initState() {
        WidgetsBinding.instance.addObserver(this);
        super.initState();
      }
    
      @override
      void dispose() {
        WidgetsBinding.instance.removeObserver(this);
        super.dispose();
      }
    
      @override
      void didChangeAppLifecycleState(AppLifecycleState state) {
        // TODO: implement didChangeAppLifecycleState
        super.didChangeAppLifecycleState(state);
        if(AppLifecycleState.paused == state) {
          /// TODO: Stop music player
        }
        print(state);
      }
    
      @override
      Widget build(BuildContext context) {
        return Container();
      }
    }