DEV Community

Harshvardhan Joshi
Harshvardhan Joshi

Posted on

A better way to listen to multiple change notifiers in Flutter

Ever done this to listen to changes from multiple (listenables/notifiers) and update your widget?

Image description

Feels cluttered and repetative for a small widget right? Imagine 3 different notifiers, or 4 or more than 5...

I know it is not an ideal situation but imagine the amount of clutter it will be for a widget to update on change of any one of the notifiers.

So, while researching about Listenable.merge(), I found a better way to do this.

Here comes AnimatedBuilder, A built-in widget in the flutter framework.

As per the flutter documentation, AnimatedBuilder is:

A general-purpose widget for building animations.

AnimatedBuilder is useful for more complex widgets that wish to include an animation as part of a larger build function. To use AnimatedBuilder, construct the widget and pass it a builder function.

For simple cases without additional state, consider using AnimatedWidget.
Enter fullscreen mode Exit fullscreen mode

Surprisingly, AnimatedBuilder does not require anything related to Animation.


Solution

All it takes is a listenable to trigger the build with latest value from any of the notifiers.

Image description

So now regardless of the number of notifiers involved in the widget, Just the use of AnimatedBuilder with Listenable.merge() has got you covered.

Adding a new notifier in the mix is now just a matter of a fewer lines modified not an entire widget level update like before.


Why This Matters

Using Listenable.merge() + AnimatedBuilder makes your code:

Cleaner: You avoid the manual hassle of listening to multiple Listenable objects separately.

More Maintainable: It’s easier to read and understand, reducing the chances of bugs.

Versatile: AnimatedBuilder works seamlessly with any Listenable, not just animations.

Give this a try next time, It’s a small change that can make a big difference in your Flutter projects!


Found this tip helpful? Share it with your Flutter community! Happy coding! πŸš€

Top comments (0)