flutteraudioaudio-playerflutter-audioplayers

How to use BLoC with just_audio


I am building a chat app and I am adding a voice message widget. I need to use BLoC with a message id to update only that message. I tried the following:

  1. Add AudioPlayer for each message with audio type to a Map and set its key to its message id.

  2. When building the audio message, I search with id in that Map and get its AudioPlayer and assign a var named player to it.

  3. In my BLoC, I have a var called id, so that I know what is the id of the current widget.

  4. In the BlocBuilder, I write the following in the buildWhen:

    buildWhen: (previous, current) {
        return id == current.id;
     },
    

    this checks if this widget's id is the same as the id which was fired by any widget, for example:

    context.read<ChatMsgBloc>().add(AudioMsgEvent(id: widget.id));
    

This is supposed to only rebuild the widget with the same id as the current state's id, and it works. each player can played and stopped. But the problem is if there is a player playing and the user plays another one without stopping the first. This will make both audios keep playing and first widget to be rebuilt 2 times. I know that this is really missed up, and I don't know how my logic would go, can someone help me?


Solution

  • I found that the best and most efficient way is just to use a ValueListenableBuilder and ValueNotifier rather than BLoC and being forced to handle when the blocbuilder is rebuilt. Each ValueListenableBuilder only listen for its ValueNotifier.