Open In App

NotificationListener Widget in Flutter

Last Updated : 08 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In Flutter, every Scrollable sends Notifications that contain information about the current scroll state. So to catch these notifications we use NotificationListener Widget. NotificationListener Widget will listen for Notifications bubbling up the tree. In this, article we will learn about NotificationListener Widget

Default Constructor:

NotificationListener({
    Key key,
    required Widget child,
    NotificationListenerCallback onNotification,
});

In the above constructor, the required type Widget Child is compulsory to give in NotificationListener.

Different kinds of Scroll Notifications:

ScrollStartNotification: The ScrollStartNotification component starts to slide.

ScrollUpdateNotification: ScrollUpdateNotification component location changed.

ScrollEndNotification: ScrollEndNotification component has stopped scrolling.

OverscrollNotification: OverscrollNotification indicates that the widget has not changed its scroll position because the change will cause the scroll position to exceed its scroll range.

Step By Step Implementation

Step 1: Create a New Project in Android Studio

To set up Flutter Development on Android Studio please refer to Android Studio Setup for Flutter Development, and then create a new project in Android Studio please refer to Creating a Simple Application in Flutter.

Step 2: Create a Container

  • Create a container and wrap it in Column Widget.
  • Inside the container, we have given height and color properties.
  • In the center of the container, the text message will be displayed.

Dart




import 'package:flutter/material.dart';
  
void main() {
  runApp(const MyApp());
}
  
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      home: const MyHomePage(),
    );
  }
}
  
class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);
  
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}
  
class _MyHomePageState extends State<MyHomePage> {
  String message = 'New';
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('GeeksforGeeks'),
        centerTitle: true,
      ),
  
      // Creating a container and giving it some styling properties
      body: Column(
        children: [
          Container(
            height: 60,
            color: Colors.orangeAccent,
            child: Center(
              child: Text(
                message,
                style: TextStyle(fontSize: 35, fontWeight: FontWeight.bold),
              ),
            ),
          ),
        ],
      ),
    );
  }
}


Step 3: Expanded widget having a child as NotificationListener

  • NotificationListener having argument onNotification will receive ScrollNotification and inside this, we will put the logic of NotificationListener
  • If ScrollNotification is ScrollStartedNotification then set message as scroll Started
  • If the user is scrolling the list then set message as scroll updated
  • If the user has ended the scrolling of the list then set message as scroll ended
  • Then at the end just return True
  • NotificationListener has child property which is of the type required. So we have to give the child to it
  • Inside the child, we are using ListView.builder having itemCount:100 and an itemBuilder which will take (context , index) and it will return List Tile displaying the Item Number

Dart




import 'package:flutter/material.dart';
  
void main() {
  runApp(const MyApp());
}
  
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      home: const MyHomePage(),
    );
  }
}
  
class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);
  
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}
  
class _MyHomePageState extends State<MyHomePage> {
  String message = 'New';
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // creating appbar
      appBar: AppBar(
        title: Text('GeeksforGeeks'),
        centerTitle: true,
      ),
  
      // Creating a container and giving it some styling properties
      body: Column(
        children: [
          Container(
            height: 60,
            color: Colors.orangeAccent,
            child: Center(
              child: Text(
                message,
                style: TextStyle(fontSize: 35, fontWeight: FontWeight.bold),
              ),
            ),
          ),
  
          // using NotificationListener Widget
          Expanded(
              child: NotificationListener<ScrollNotification>(
  
            onNotification: (scrollNotification) {
              // Logic of scrollNotification
              if (scrollNotification is ScrollStartNotification) {
                setState(() {
                  message = 'Scroll Started';
                });
              } else if (scrollNotification is ScrollUpdateNotification) {
                setState(() {
                  message = 'Scroll Updated';
                });
              } else if (scrollNotification is ScrollEndNotification) {
                setState(() {
                  message = 'Scroll Ended';
                });
              }
              return true;
            },
            // child of type required. Which means its compulsory to pass in NotificationListener
            child: ListView.builder(
                itemCount: 100,
                itemBuilder: (context, index) {
                  return ListTile(
                    title: Text('Item: $index'),
                  );
                }),
          ))
        ],
      ),
    );
  }
}


Output:

As you can see when I started scrolling the message displayed was Scroll Updated and as soon as I stopped scrolling the message displayed was Scroll Ended.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads