NotificationListener widget and Attributes

NotificationListener widget and Attributes

ยท

2 min read

The NotificationListener widget in Flutter is used to listen for notifications dispatched by descendant widgets in the widget tree. It allows you to intercept and respond to notifications, such as scroll events, focus changes, or custom notifications.

Attributes:

  1. child (Widget):

    • The child widget for which the notifications are being listened.
  2. onNotification (bool Function(T notification)):

    • A callback function that is called when a notification is dispatched. It takes the dispatched notification as an argument and returns a boolean value indicating whether the notification should be absorbed (true) or not (false).
  3. behavior (HitTestBehavior):

    • Determines how the listener should behave during hit testing. Options include HitTestBehavior.deferToChild, HitTestBehavior.translucent, and HitTestBehavior.opaque.

Example:

import 'package:flutter/material.dart';

class ScrollNotificationListener extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('NotificationListener Example'),
      ),
      body: NotificationListener<ScrollNotification>(
        onNotification: (notification) {
          if (notification is ScrollStartNotification) {
            print('Scroll Start');
          } else if (notification is ScrollUpdateNotification) {
            print('Scroll Update - Offset: ${notification.metrics.pixels}');
          } else if (notification is ScrollEndNotification) {
            print('Scroll End');
          }
          // Return true to absorb the notification
          return false;
        },
        child: ListView.builder(
          itemCount: 50,
          itemBuilder: (context, index) {
            return ListTile(
              title: Text('Item $index'),
            );
          },
        ),
      ),
    );
  }
}

void main() {
  runApp(
    MaterialApp(
      home: ScrollNotificationListener(),
    ),
  );
}

In this example, a NotificationListener is used to listen for ScrollNotification events in a ListView. The onNotification callback is invoked whenever a scroll event occurs (start, update, or end). You can customize the behavior based on the type of notification received. The NotificationListener allows you to respond to various notifications and take specific actions in your Flutter application.

Did you find this article valuable?

Support Vinit Mepani by becoming a sponsor. Any amount is appreciated!

ย