I have initial data which works fine.
var data = {field1: FieldValue.increment(1)};
And it is also fine when I add another field to the data.
data.addAll({field2: FieldValue.increment(1)});
But if I set the value to 0, it won’t allow me to.
data.addAll({field3: 0});
It will give an error of:
The element type ‘int’ can’t be assigned to the map value type ‘FieldValue’.
I tried doing this but still, have the same issue.
data[field3] = 0;
How will I set the field3
to a specific value?
Note:
This is the full code.
DocumentReference<Map<String, dynamic>> ref = db.collection('MyCollect').doc(uid);
var data = {field1: FieldValue.increment(1)};
data.addAll({field2: FieldValue.increment(1)});
data.addAll({field3: 0});
ref.set(data, SetOptions(merge: true));
2
Answers
check your dart type.
Difference between "var" and "dynamic" type in Dart?
the type var can’t change type of variable. so check your code.
maybe data’s type fixed something <String, FieldValue>
you can try dynamic type.
For a better understanding
you can use the
var
keyword when you don’t want to explicitly give a type but its value decides its type, and for the next operations/assignments, it will only accept that specific type that it took from the first time.On the other hand, the
dynamic
keyword is used also to not explicitly set a type for a variable, but every other type is valid for it.in your case, you’re using the
var
keyword, so in the first value assignment it takes its type:However, you can fix the problem and let your
data
variable accept any kind of element types by either using thedynamic
keyword:or, specifying that this is a
Map
, but the values of it aredynamic
:Hope this helps!