0

I have a TabBarView that hold 3 children, one of them contains audio player widget.

      length: 3,
      child: Scaffold(
        appBar: AppBar(widget.title, myTabs),
        body: TabBarView(
          children: [
            ChildrenA(),
            ChildrenB(),
            ChildrenC(),           
          ],
        ),
      ),
    );

ChildrenA is a statefull widget that contains ListView. One element in ListView is my AudioPlayer. Im using this widget https://pub.dev/packages/just_audio to play audio.

      addAutomaticKeepAlives: true,
      itemCount: awaitedContents!.length,
      itemBuilder: (context, index) {
        Content content = awaitedContents[index];
        ...
          return AudioContent(content.value),
          );
        }

Question is, how do i stop audio from playing when i switch tabs? It seems that dispose is not called during tab switch. Only if I go back to previous screen in route.

sylikon
  • 115
  • 1
  • 9

1 Answers1

1

Try passing a TabController as an argument to the TabBarView. Add a listener to the tabController like this:

  @override
  void initState() {
    _tabController.addListener(() {
       stopAudio();
    });
    super.initState();
  }

So if something in your TabBarView changes the audio will stop

Matheus Melo
  • 172
  • 9
  • This approach worked. I didn't have immediate access to audio player that was instantiated in child widget. Solution from this answer was helpful https://stackoverflow.com/questions/58159655/access-child-widgets-variable-in-parent-widget-flutter-with-dart – sylikon Oct 12 '22 at 09:07