如何使用Flutter执行Firebase可变事务数据?

时间:2017-11-21 00:06:36

标签: firebase firebase-realtime-database transactions flutter nsmutabledata

我有Swift代码,我在某些条件下减少或增加int值。我怎么能用Flutter复制这个?这是我的Swift代码..

//  2.  Decrease Value -= from NumberOnes
let decreaseRef = self.ref.child("NumberOnes/\(myfav1)/Value")
decreaseRef.runTransactionBlock { (currentData: FIRMutableData) -> FIRTransactionResult in
    if var data = currentData.value as? Int
    {
        var count = data
        count -= 1
        data = count
        currentData.value = data
        return FIRTransactionResult.success(withValue: currentData)
    }
    return FIRTransactionResult.success(withValue: currentData)
}

此外,如果有相关的文档/教程,请指出。

*更新*

这是我的Flutter代码......

fb.child('UserVideo/${userid}/Vid1').onValue.listen((Event event){
        if (event.snapshot != null){
          final vidID = event.snapshot.value["videoID"];
          fb.child('NumberOnes/${vidID}/Value').onValue.listen((Event newEvent){
            int vidValue = newEvent.snapshot.value;
            vidValue;
            print(vidValue);
            //vidValue = value;
            final value = vidValue--;

            fb.child('NumberOnes/${vidID}').update({
              'Value': value,
            });

          });

我的Flutter代码的问题在于它不会停止减少。有办法解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

这是我的解决方案。我在这里从这个答案中解决了...... Flutter Firebase update will not stop updating node?

基本上,我将值隔离一次,操纵它,然后用新信息更新节点。我认为这比Firebase Swift SDK中的runTransactionBlock效率低得多,后者将快照值作为MutableData返回。如果有人在将来找到解决方法,请添加答案。

if (vidRank == 1) {
  var event = await fb.child('UserVideo/${userid}/Vid1').once();
  if (event.snapshot != null){
    var vid1id = event.snapshot.value['videoID'].toString();
    var onesEvent = await fb.child('NumberOnes/${vid1id}').once();
    if (onesEvent.snapshot != null){
      var onesValue = (onesEvent.snapshot.value['Value'] as int);
      final vidValue = onesValue - 1;
      print("Inside  ${vidValue}");
      fb.child('NumberOnes/${vid1id}').update({
        'Value': vidValue
      });
    }
  }
}