How to use Flutter Notifications to build your widgets
Notifications — is a tool Flutter uses to pass any kind of data higher in the widget tree hierarchy. Somewhere in depth of your widget tree you can fire a notification and it will go up, like a bubble.
How can I use them?
If a notification is fired, you can “catch” it in the widget tree above by using a NotificationListener
widget. Remember the ScrollNotification
class? Yep, that’s the kind of notifications we’re talking about.
That onNotification
callback takes a notification object as a parameter and require you to return a boolean. This boolean is an indicator whether the notification is allowed to keep going up in the widget tree.
Can I define my own notifications?
Yes! All you need to do is to create a class and to extend it from the Flutter’s Notification
class:
Now you are able to dispatch your notifications using a BuildContext
object:
Parents of that widget can catch it up by using a NotificationListener
:
How do I build the UI using it?
One of the ways is to use a NotificationListener
in a StatefulWidget
. You catch a notification, you update your state. Simple. Let’s use that MyNotification
class that we’ve created.
Surely, we could just put that TextButton
in the Column
without defining a separate widget. But imagine that button is placed somewhere in the depth of the widget tree. In this case you should split your widgets into smaller ones. And this small example illustrates how you can use notifications to pass the data up in the tree.
But there’s another way…
Instead of creating stateful widgets or using change notifiers, we could use the notification_builder package. It gives us a builder callback. It is similar to onNotification
in the NotificationListener
, but is used to render the UI.
Let’s refactor our code above to use a NotificationBuilder
:
Neat. Now the NotificationBuilder
is handling the state for us. So we don’t need to create a stateful widget ourselves.
However, under the hood, it works just in the way we implemented higher: it’s a stateful widget that uses a NotificationListener
.
You can find the source code on GitHub a colorful example.
Conclusion
Notifications is a good tool I discovered recently. Well, I definitely knew about notifications like ScrollNotification
, but then I learned that we’re allowed to define our own notifications.
Now, instead of passing callbacks or ChangeNotifier
s to the child widgets, we can use notification to pass the data up in the tree from the widgets below. Another way is to use an InheritedWidget
… But it’s a different topic.
Reach out to me in Telegram or join my technical blog there.