首页 > 解决方案 > Firestore 侦听器未按预期工作

问题描述

我的 Web 应用程序要求我对文档 jkl 使用 firestore 侦听器。即使文档 jkl 中没有更新,它也会重复打印该值,而不是打印一次更新的值。

void switchListener() async 
{
  _listener = Firestore.instance
  .collection('abc')
  .document('def')
  .collection('ghi')
  .document('jkl')
  .snapshots()
  .listen((data) => listenerUpdate(data));
}

void listenerUpdate(data) 
{
   String number = data['URL'];
   setState(() {
     _totalDocs = number;
   });
 }

我能得到一些帮助吗?

更新

只有在单击按钮后才会激活侦听器。

onPressed: () {
   switchListener();  
},

void switchListener() async {
  _listener = Firestore.instance
      .collection('abc')
      .document('def')
      .collection('jkl')
      .document('mno')
        .snapshots()
        .distinct()
        .listen((data) => listenerUpdate(data));

  _listener.cancel();

 }

void listenerUpdate(data) {
    String number =  data['physicianNote'];
    String url =  data['signedURL'];
    setState(() {
      _totalDocs = number;
      _signedurl = url;
    });
    print("totalDoc: "+_totalDocs);
    print("url: "+_signedurl);
    js.context.callMethod("open", [signedurl]);

  }

标签: firebaseflutterdartgoogle-cloud-firestore

解决方案


如果它们等于先前的数据事件,您可以尝试在跳过数据事件的distinct()方法之后添加该方法。您可以从官方文档snapshots()中了解更多信息。

void switchListener() async 
{
  _listener = Firestore.instance
  .collection('abc')
  .document('def')
  .collection('ghi')
  .document('jkl')
  .snapshots()
  .distinct() // Will only emit if `snapshots()` emits different data
  .listen((data) => listenerUpdate(data));
}

void listenerUpdate(data) 
{
   String number = data['URL'];
   setState(() {
     _totalDocs = number;
   });
 }

推荐阅读