The element type 'int' can't be assigned to the map value type 'FieldValue' when trying to assign a new value

Mr.*_*cio 2 dart firebase flutter

I have initial data which works fine.

var data = {field1: FieldValue.increment(1)};
Run Code Online (Sandbox Code Playgroud)

And it is also fine when I add another field to the data.

data.addAll({field2: FieldValue.increment(1)});
Run Code Online (Sandbox Code Playgroud)

But if I set the value to 0, it won't allow me to.

data.addAll({field3: 0});
Run Code Online (Sandbox Code Playgroud)

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;
Run Code Online (Sandbox Code Playgroud)

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));
Run Code Online (Sandbox Code Playgroud)

Gwh*_*yyy 5

为了更好的理解

var当您不想显式给出类型但其值决定其类型时,可以使用关键字,并且对于下一个操作/分配,它将仅接受第一次采用的特定类型。

另一方面,dynamic关键字也用于不显式设置变量的类型,但所有其他类型对其都有效。

var a = "text";
a = "text2"; // ok
a = 1; // throws the error

dynamic b = "text";
b = "text2"; // ok
b = 1; // also ok
Run Code Online (Sandbox Code Playgroud)

在您的情况下,您使用的是var关键字,因此在第一个值赋值中它采用其类型:

var data = {field1: FieldValue.increment(1)}; // takes the Map<String, FieldValue> type
data.addAll({field3: 0}); // 0 is int and FieldValue.increment(1) is FieldValue type,  so it throws an error
Run Code Online (Sandbox Code Playgroud)

但是,您可以data使用dynamic关键字解决该问题并让您的变量接受任何类型的元素类型:

dynamic data = {field1: FieldValue.increment(1)}; // will accept it.
Run Code Online (Sandbox Code Playgroud)

或者,指定这是 a Map,但它的值为dynamic

Map<String, dynamic> data = {field1: FieldValue.increment(1)}; // will accept it also.
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!