简体   繁体   English

Flutter Firebase RTDB onValue 多次触发

[英]Flutter Firebase RTDB onValue triggered multiple times

I'm developing an app which needs live data from the database which was created using Firebase RTDB.我正在开发一个应用程序,它需要来自使用 Firebase RTDB 创建的数据库的实时数据。 I used onValue to get the live data, the problem is that the onValue is triggered multiple times when a lot of data changed at once and messed up my data processing system.我使用 onValue 来获取实时数据,问题是当大量数据同时更改时会多次触发 onValue 并弄乱了我的数据处理系统。 Been trying to look for solutions, but still haven't managed to find one.一直在尝试寻找解决方案,但仍未找到解决方案。 Any help will be appreciated.任何帮助将不胜感激。 Here's the code:这是代码:

await refConnection
        .child(user!.uid).orderByChild('date_created').onValue.forEach((element) {
          if (element.snapshot.value != null) {
            Map<dynamic, dynamic> connection = element.snapshot.value as Map<
                dynamic,
                dynamic>;
            print("Test: $connection");
            

            connection.forEach((key, value) {
              if (connection[key]['status'] == 'connected') {
                Provider.of<ContactDataProvider>(context, listen: false)
                    .addConnected(connection[key]);
              } else if (connection[key]['status'] == 'incoming_req') {
                Provider.of<ContactDataProvider>(context, listen: false)
                    .addIncoming(connection[key]);
              } else if (connection[key]['status'] == 'sent_req') {
                print(connection[key]);
                Provider.of<ContactDataProvider>(context, listen: false)
                    .addSent(connection[key]);
              }
            });

            setState();
          }
    });

Do you really need to listen for live updates?您真的需要收听实时更新吗? If not, then try getting the value only once using get() .如果不是,则尝试使用get() 仅获取一次值

Solution: Trying with a different approach解决方案:尝试不同的方法

Can you please provide an example about your user child structure?您能否提供有关您的用户子结构的示例?

As I can determine by your code, do you have multiple items with different data inside your user child, each data with a field called status ?正如我可以通过您的代码确定的那样,您的用户子项中是否有多个具有不同数据的项目,每个数据都有一个名为status的字段?

If that is correct, then you should use onChildChanged listener to list only when a child inside userId is changed.如果那是正确的,那么您应该使用 onChildChanged 侦听器仅在 userId 中的孩子发生更改时列出。

That will be triggered when any child inside userId change its value, then you can verify if the childChanged.key == status then do your logic当 userId 中的任何孩子更改其值时将触发,然后您可以验证 childChanged.key == status 然后执行您的逻辑

But keep aware of the fact that any value changed inside userId child, will trigger your listener.但请注意,userId 子项内部的任何值更改都会触发您的侦听器。

avoid cyclic calls避免循环调用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM