Flutter How to Pop out page automatically according to stream event?

Issue

I want to pop out a music player page when the audio stream is stopped. But I am getting error like

Unhandled Exception: Looking up a deactivated widget's ancestor is unsafe

This is my code which I have placed inside the build method before returning scaffold.

AudioService.playbackStateStream.listen((event) {
      if (event?.processingState == AudioProcessingState.stopped) {
        
        try {
          final modal = ModalRoute.of(context);
          if (modal.isCurrent) {
            Navigator.of(context).pop();
          }
        } catch (e) {
          print("exception error in player adv $e");
        }
      }
    });

Solution

Try moving that to initState() it’s possible that everytime the widget rebuilds, the listener is added, therefore you end up having multiple listeners and when triggered would call pop multiple times

Answered By – faithomotoso

Answer Checked By – Cary Denson (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *