Home > database >  Issue with fetching number value from Firestore
Issue with fetching number value from Firestore

Time:07-01

I have a function :

  final ref= FirebaseFirestore.instance.collection('test').doc('t');

  Future _custom()async{
    await ref.update({'t':FieldValue.increment(1)});
    await ref.get().then((last) => print(last.data()!['t']));
    return;
  }

With a button onPressed method, I called the function continuously many times. I expect result be like:

1
2
3
4
5

But, I got this:

1
1
3
3
4
4
7

While I made the clicks much faster, the result goes terribly wrong. But, when get slower it comes more accurate.

CodePudding user response:

While the FieldValue.increment(x) will ensure that there are no overlapping write conflicts, the method in which you read the number out will give you false results.

If you check your data after all the increments you will see that it is correct.

If you wanna ensure that your user gets the right number displayed you can increment your local application state on click, kind of like a optimistic write.

https://firebase.google.com/docs/firestore/manage-data/add-data#dart_12

Warning. Increment operations are useful for implementing counters, but keep in mind that you can update a single document only once per second.

CodePudding user response:

You simply replace by this await ref.set({'t':FieldValue.increment(1)},isMerged:true);

  • Related