【问题标题】:How to check if new data added in to firebase collection in flutter如何检查是否在颤动中将新数据添加到firebase集合中
【发布时间】:2022-11-04 04:12:43
【问题描述】:

如何知道是否有新数据添加到 Firebase 集合中。

我的问题是当新数据添加到 firebase 集合时我需要推送通知。 这是我的代码样子。 我知道如果我把这段代码放到我创建firebase集合的函数中它会起作用。 但在这种情况下,我想在这里编写代码。 我怎么做 。这是我尝试过的代码

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();
        });

我该怎么做呢

这个问题的解决方案

【问题讨论】:

  • 云功能触发器是解决方案。 StreamBuilder 仅用于根据获取的数据呈现 UI。不是为了触发函数

标签: flutter dart flutter-notification


【解决方案1】:

您可以通过以下方式访问自上次快照以来的文档更改:

snapshot.data.docChanges

这将为您提供List&lt;DocumentChange&lt;Object?&gt;&gt;,您可以检查列表中的每个项目,并确定更改的类型,例如第一个的类型是:

snapshot.data.docChanges[0].type

您需要将上述值与以下值之一进行比较,每个值代表相应的变化:

DocumentChangeType.added
DocumentChangeType.modified
DocumentChangeType.removed

把它放在一起,在确保snapshot.hasData 是true 之后,你可以这样做:

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

【讨论】:

    猜你喜欢
    • 2021-11-02
    • 1970-01-01
    • 2021-10-09
    • 1970-01-01
    • 1970-01-01
    • 2019-09-15
    • 1970-01-01
    • 2021-12-12
    • 1970-01-01
    相关资源
    最近更新 更多