Event Handling with NotificationListener in Flutter
Jatin kumar Sahoo
Flutter Web Developer at Skillmine ( Flutter || Dart || GETX || Provider || Bloc || Android || IOS || Flutter WEB ||AWS APP SYNC || Firebase Crashlytics || Google Map SDK) Flutter Developer
NotificationListener<T> is a widget in Flutter that listens for notifications of type T and allows you to respond to events (e.g., scroll events, layout changes) within a widget subtree.
Example: Listening to Scroll Events
In this example, we listen to ScrollNotification to detect scroll changes in a ListView:
NotificationListener<ScrollNotification>(
onNotification: (notification) {
if (notification is ScrollUpdateNotification) {
final scrollPosition = notification.metrics.pixels;
print("Scroll position: $scrollPosition");
}
return false; // Allow the notification to propagate
},
child: ListView.builder(
itemCount: 100,
itemBuilder: (context, index) => ListTile(title: Text('Item $index')),
),
);
How It Works:
领英推荐
Example: Custom Notification
You can also create custom notifications to handle specific events.
class MyCustomNotification extends Notification {
final String message;
MyCustomNotification(this.message);
}
NotificationListener<MyCustomNotification>(
onNotification: (notification) {
print('Custom notification: ${notification.message}');
return true; // Stop propagation
},
child: ElevatedButton(
onPressed: () {
MyCustomNotification('Hello!').dispatch(context);
},
child: Text('Send Notification'),
),
);
How It Works:
Key Benefits:
In short, NotificationListener allows you to easily handle various events and notifications in Flutter apps.