skip to Main Content

I have the following structure for my app, where ChatScreen contains the ChatHeader and the ChatFooter.

                   ---ChatHeader.dart --- MessageDao.dart
ChatScreen.dart ---
                   ---ChatFooter.dart

In the ChatHeader widget, I call another widget called MessageDao.dart. This widget generates the button that the user can press on the ChatHeader widget to play audio.

In the ChatFooter widget, this widget contains a different button that the user can press to record using their mic.

When I play audio using the button from ChatHeader -> MessageDao, this works just fine. However, if I click the button in the ChatFooter widget to start recording while in the middle of playing audio from the first button, this audio doesn’t stop playing. It keeps playing while I’m recording. I have a stopPlaying() function in MessageDao that I can use, but I’m not sure how to call a function in widget A from widget B.

Or in other words, how do I call MessageDao.stopPlaying() from inside ChatFooter.dart?

2

Answers


  1. You can use some event mechanism to notify MessageDao about an event in your app, e.g., AudioRecordingStartedEvent.

    1. On MessageDao you subscribe on the event and stop the playing audio,
    2. On ChatFooter you fire the event.

    On pub.dev a lot of libraries that implement EventBus, e.g. event_bus_plus

    Login or Signup to reply.
  2. With this type of situation, the ideal solution is to take a page out of React and ‘lift the state up‘; this means that whatever method is on the child should be lifted to a higher node in the widget tree (e.g. ChatScreen) and then pass the function down to the nodes that use it (ChatHeader and ChatFooter). You could also try leveraging InheritedWidget after ‘lifting state up’ and avoid sending methods down a chain of widgets.

    Now, this is a recurring theme with Flutter apps (and overall declarative frameworks) and is a problem that can have multiple solutions. My suggestion would be that you take a look at different state management options like bloc, provider, mobx, riverpod, rxdart, redux or event_bus_plus just to mention a few. Said libraries will give you the abstractions you need for each use case and help you avoid implementing really complex logic that you might need to solve problems similar to this one by yourself.

    Of course, this is an important decision for your project so I suggest you take a good look and choose whatever you feel comfortable with or is similar to something you have worked on before.

    Good luck my fellow Flutter developer, choose wisely 😛

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search