Search code examples
flutterdartflutter-notification

How to check if new data added in to firebase collection in flutter


how to know if a new data added in to firebase collection.

my question is i need to push notification when the new data added to the firebase collection. here is my code look like. and i know it will work if i put this code in to the functin where i create the firebase collection. but in this case i want to code this here. how do i do that . here is the code i tried

StreamBuilder<List<StudentNotificationModel>>(
        stream: _notificationImplementaion.readNotification(),
        builder: (context, snapshot) {
          final notification = snapshot.data;
          if (snapshot.hasError) {
            return const MessageWidget('Please Try Again');
          }
          if (snapshot.hasData) {
            if (snapshot.data == null || snapshot.data!.isEmpty) {
              return Text('empty')
            }
            // what should i check here?
            if (newdata.added) {
              log('New Data added');
              pushNotificationCode();
            }
            return Expanded(
              child: ListView.builder(
                physics: BouncingScrollPhysics(),
                shrinkWrap: true,
                itemCount: notification.length,
                itemBuilder: (context, index) {
                  final data = notification[index];
                  return HomeTile(
                    subtitle: data.notificationType,
                    title: data.title,
                    accountType: accountType,
                  );
                },
              ),
            );
          }
          return const Loading();
        });

how do i do this

solution of this problem


Solution

  • You can access the document changes since the last snapshot with:

    snapshot.data.docChanges
    

    This will give you a List<DocumentChange<Object?>> and you can check each item in the list, and determine the type of the change, for example the first one's type will be:

    snapshot.data.docChanges[0].type
    

    You need to compare the above value with one of the following, each representing the corresponding change:

    DocumentChangeType.added
    DocumentChangeType.modified
    DocumentChangeType.removed
    

    Putting it together, after making sure that snapshot.hasData is true, you can do something like this:

    for (var change in snapshot.data!.docChanges) {
      if (change.type == DocumentChangeType.added) {
        // do your logic here
      }
    }