Mr. Tacio
Mr. Tacio

Reputation: 562

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

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));

Upvotes: 2

Views: 1151

Answers (2)

Gwhyyy
Gwhyyy

Reputation: 9166

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.

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

dynamic b = "text";
b = "text2"; // ok
b = 1; // also ok

in your case, you're using the var keyword, so in the first value assignment it takes its type:

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

However, you can fix the problem and let your data variable accept any kind of element types by either using the dynamic keyword:

dynamic data = {field1: FieldValue.increment(1)}; // will accept it.

or, specifying that this is a Map, but the values of it are dynamic:

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

Hope this helps!

Upvotes: 5

rodpold
rodpold

Reputation: 166

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.

var data = {field1: FieldValue.increment(1)};

maybe data's type fixed something <String, FieldValue>

you can try dynamic type.

Upvotes: 3

Related Questions