【问题标题】:how to see changes of voteCount with StreamProvider如何使用 StreamProvider 查看 voteCount 的变化
【发布时间】:2021-02-03 12:06:47
【问题描述】:

我有一个产品列表的 StreamProvider 和 Firestore 数据

 StreamProvider<List<Product>>.value(
        value: DatabaseService().products,
      ),

现在我有这个产品列表的详细信息页面 如果我单击详细信息页面的列表,我会向详细信息页面提供一个对象

DetailsPage(courseData: product)

我需要在此详细信息页面中创建一个赞成按钮,以便它也可以更改 Firestore 数据

  if (voted) {
        FirebaseFirestore.instance
            .collection('products')
            .doc('${widget.courseData.id}')
            .update({"voteCount": widget.courseData.voteCount - 1});
      } else {
        FirebaseFirestore.instance
            .collection('products')
            .doc('${widget.courseData.id}')
            .update({"voteCount": widget.courseData.voteCount + 1});
      }
      isVoted = !isVoted;
    } catch (e) {
      print(e.message);
    }

如果点击upvote按钮,这里的courseData不会改变,因为它的值不是来自streamProvider而是来自

详细信息页面(课程数据:产品)

我该如何解决这个问题

【问题讨论】:

    标签: flutter dart google-cloud-firestore flutter-provider


    【解决方案1】:

    我建议您使用increment() 操作来完成相同的操作,而不是传入您不知道的新值。

    if (voted) {
        FirebaseFirestore.instance
            .collection('products')
            .doc('${widget.courseData.id}')
            .update({"voteCount": firebase.firestore.FieldValue.increment(-1) });
    } else {
        FirebaseFirestore.instance
            .collection('products')
            .doc('${widget.courseData.id}')
            .update({"voteCount": firebase.firestore.FieldValue.increment(1) });
        }
        isVoted = !isVoted;
    } catch (e) {
      print(e.message);
    }
    

    除了不需要知道当前值(我认为这是你的问题)之外,它在离线和多用户场景中也能更好地工作。

    【讨论】:

    • widget.coursedata.id 值不会实时更新,因为它只从父对象获得值,所以我也希望它改变
    • 现在我可以更改数据,但问题是显示实时更改,但是当我从类中获取数据作为对象时。我没有改变我已经离开页面并重新点击卡片以更新页面。
    猜你喜欢
    • 2021-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-01
    • 2021-05-21
    • 2020-08-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多