notification_hub
An event broadcasting mechanism designed for dispatching notifications to registered subscribers, inspired by the structure of the iOS Notification Center.
Video demo showcasing its usage
Explanation
There are three notification channels: Mammals, Insects, and Birds.
Widget Asubscribes to the Mammals notification channel.Widget Bsubscribes to the Insects notification channel.Widget Csubscribes to the Insects notification channel.Widget Dsubscribes to both the Mammals and Birds notification channels.
When a Dog is posted, Widget A and D will receive it.
When Bees are posted, Widget B and C will receive the notification.
If an Owl is posted, only Widget D will receive the notification.
Getting Started
notification_hub is available through pub.dev.
Add the Dependency
To use notification_hub in your Flutter project, add the following dependency to your pubspec.yaml file:
dependencies:
...
notification_hub: ^1.0.3
Usage example
For a detailed usage example, check the example folder.
Subscribe Observer (Subscribe to a single notification channel)
Create a notification channel (e.g 'Greetings'), subscribe then listen to events.
NotificationHub.instance.addSubscriber(object: this, notificationChannel: 'Greetings',
onData: (data) {
debugPrint("$data");
});
Here's a breakdown of each part:
addSubscriber: This method is used to subscribe an object (in this case, the current object, represented by this) to a specific notification channel. The this can also be replaced by an instance of an object.
notificationChannel: 'Greetings' Specifies the name of the notification channel to which the object is subscribing. In this case, it's 'Greetings'.
onData: This is a callback function that will be executed when new data is received on the 'Greetings' channel. The data parameter represents the data received.
Subscribe Observer (Subscribe to multiple notificaiton channels)
NotificationHub.instance.addSubscriber(object: this, notificationChannel: 'Morning',
onData: (data) {
debugPrint("$data");
});
NotificationHub.instance.addSubscriber(object: this, notificationChannel: 'Afternoon',
onData: (data) {
debugPrint("$data");
});
Unsubscribe
Unsubscribe by caling removeSubscriber.
Unsubscribe from All notification channels
NotificationHub.instance.removeSubscriber(object: this);
Post notification
NotificationHub.instance.post(notificationChannel:'Greetings', data: 'Hello');