Home > Blockchain >  Adding a fixed value in a map
Adding a fixed value in a map

Time:11-21

I have an initial data which works fine.

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

And it is also fine when I add another field on 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 having 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));

CodePudding user response:

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!

CodePudding user response:

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.

  • Related