Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FieldValue.increment for Cloud Firestore in Flutter

I'm creating a android app using flutter and Firebase Firestore. I would like to add that new FieldValue.increment functionality which is apperently available in Firebase since this april but i've got an error: The method 'increment' isn't defined for the class 'FieldValue'.

Here is my code that i've tried:

onTap: (){
  Firestore.instance.document('docRef').updateData({"numberOfDocs": FieldValue.increment(1)});
}

I'm just a beginner programmer but when i checked that field_value.dart file it's missing "increment" implementation. So, is it right answer to say that flutter team didn't yet implemented that functionality?

I've seen a tutorial where increment is already used in some .js code but for me it's not working. https://www.youtube.com/watch?v=8Ejn1FLRRaw

like image 953
Hodofca Avatar asked Apr 14 '19 13:04

Hodofca


People also ask

How do I increment a number in firestore?

Firestore now has a specific operator for this called FieldValue. increment() . By applying this operator to a field, the value of that field can be incremented (or decremented) as a single operation on the server.


3 Answers

User that Import:

import 'package:cloud_firestore/cloud_firestore.dart';

For Increment:

await FirebaseFirestore.instance.collection('post').doc(postId).update({"like": FieldValue.increment(1)});

For Decrement:

await FirebaseFirestore.instance.collection('post').doc(postId).update({"like": FieldValue.increment(-1)});
like image 196
Sohaib Aslam Avatar answered Oct 05 '22 19:10

Sohaib Aslam


This has been added to the cloud_firestore Flutter plugin as of version 0.10.0.

You can use FieldValue.increment with a double (e.g. FieldValue.increment(1.0)) or an int (e.g. FieldValue.increment(2)).


Here is the relevant pull request.

If anyone reads this before the version is pushed to Pub: The link to the version will not yet work, but in the meantime you can use this Git commit, which contains a fix I did.

like image 21
creativecreatorormaybenot Avatar answered Oct 05 '22 18:10

creativecreatorormaybenot


As far as I can see in the change log for FlutterFire, the increment operator has not been added yet.

I added a feature request to the repo.

like image 35
Frank van Puffelen Avatar answered Oct 05 '22 19:10

Frank van Puffelen