Expected a value of type 'int', but got one of type 'String' when trying to add a new key,value to a map - flutter

I have a map like this:
map = {
'container_1':0,
'container_2':0,
'container_3':0,
}
That's being created from an iterable like this:
map=Map.fromIterable(containerList, key: (e)=>e, value: (e)=>0);
But when I try to add this key and value, I get an error:
map['user']='User Name';
The error I get is:
Expected a value of type 'int', but got one of type 'String'
How do I add a key value to a map that has a different value type than what's already in it?

The type of the map variable is Map<String, int>, so you couldn't add a String value to it. If you can change map type to Map<String, Object> then you will be able to add String value to it. Like this:
final map = <String, Object>{
'container_1': 0,
'container_2': 0,
'container_3': 0,
};
map['user'] = 'User Name';

I'd prefer to initialize the map to have The key as String and the value as dynamic
Because the dynamic makes your variable type to be determined at the run type with any errors
final map = <String, dynamic>{
'container_1': 0,
'container_2': 0,
'container_3': 0,
};
map['user'] = 'User Name';

Related

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

Convert data Type into different data Type in dart

I am working in backend using dart. when i get a request i check the data type of all the values in key value pair. some times i receive data type.
_InternalLinkedHashMap<String, dynamic>
I need a where i can type cast a data-type
Type xyz = sumFunction(_InternalLinkedHashMap<String, dynamic>);
print(xyz);
output :
Map<String,dynamic>
Beacause when i am comparing
print(_InternalLinkedHashMap<String, dynamic> == Map<String,dynamic>);
output:
false
If anyone have any kind of solution please provide.

check if the map has a specific string in it's keys, then give me it's value, that belong this key, Dart

may i ask how to check if the map of String,String has in it's keys a specific String
then i want to get the value that belong this specific key that contains the target String.
for example
this Map
Map<String, String> ListFinalAllInfos = {'stackoverflow': 'one', 'google': 'two'};
and i want to check if this map has this String in it's keys
stackoverflow
if stackoverflow exists as a key inside the map then i want to get the value
which is
one
without converting the map to a list, if this possible.
thanks in advance
Map<String, String> ListFinalAllInfos = {'stackoverflow': 'one', 'google': 'two'};
String key = ListFinalAllInfos.containsKey("stackoverflow"); // search for the key. for example stackoverflow
String value = ListFinalAllInfos[key]; // get the value for the key, value will be 'one'
if(ListFinalAllInfos.containsKey(value)){ //check if there is a key which is the value you grabbed
return true;
}
You can use the containsKey(Object? key) method of map to know whether it is having a matching key. This method returns true if this map contains the given [key]. So in context to your question, to check whether map has this key just use:
final hasKey = listFinalAllInfos.containsKey("stackoverflow");
Now you know whether the map has the key or not. Based on that, to get value of respective key just use:
final valueOfKey = listFinalAllInfos["stackoverflow"];
This will return you the value associated to the key in the map.

Get index of list of map from map

How do you get index of list of maps from a map. I tried to use indexOf which works but by the time the position of values are mixed up then it returns -1.
UPDATE: It actually doesn't work even in right order
List<Map<String, dynamic>> list = [{'id':1, 'name':'a'}, {'id':2, 'name':'b'}];
Map<String, dynamic> item = {'name':'a','id':1}; //<- position name and id are in different places
print(list.indexOf(item)); // so it return -1
The best way would be to get index of list where item contains same id ... if you know what I mean... How to do it?
You can use indexWhere instead indexOf.
Map<String, dynamic> item = {'name':'a','id':1};
print(list.indexWhere((i) => i['id'] == item['id'])); // prints 0
Map<String, dynamic> item = {'name':'b','id':2};
print(list.indexWhere((i) => i['id'] == item['id'])); // prints 1

Handle null value in Dart / Flutter

I have this User class and then a Firestore Document, that may or may not contain a photoURL or some other values. The problem is, that when I try to create an user I get this exception because some of the values are Null.
I've tried to handle it like this:
var photoURL = snapshot.data['photoURL'] ??= '';
but it seems it doesn't work.
Can anyone explain best practices handling Null values in Dart/Flutter respectively?
EDIT: I'm checking if snapshot.exists before and if I create the user omitting the values I know are Null, it creates it properly.
EDIT 2: I've found the problem appears when I try to handle empty List like this:
var favorites = snapshot.data['favorites'] ?? [''];
It seems I was initialized the value the wrong way when I converted it to Json.
I handle the empty Array like this
Map<String, dynamic> toJson() => {
'favorites' : favorites ?? '',
}
when it should be:
Map<String, dynamic> toJson() => {
'favorites' : favorites ?? [''],
}
So it was throwing when I tried to assign an empty Array to String.