Event Handling with NotificationListener in Flutter

Event Handling with NotificationListener in Flutter

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:

  • ScrollNotification: The NotificationListener listens for scroll-related notifications like ScrollUpdateNotification.
  • Callback: When a scroll event occurs, the onNotification callback is triggered, where you can capture the scroll position.
  • Returning false: This allows the notification to continue propagating.

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:

  • Custom Notification: MyCustomNotification is created to carry a message.
  • Dispatch: The notification is dispatched when the button is pressed, and the listener reacts to it.

Key Benefits:

  • Event Propagation: Capture events like scrolling or custom actions across widget hierarchies.
  • Decoupling Widgets: Parent widgets don’t need to be aware of child widget events.

In short, NotificationListener allows you to easily handle various events and notifications in Flutter apps.

要查看或添加评论,请登录

Jatin kumar Sahoo的更多文章

社区洞察

其他会员也浏览了