Reputation: 1011
Refer My code:In dart When I try to assign value map in the params map cleintRequest I got this exception, Anybody please guide me
const Map<String, int> value = {"resourceExpiredHour": 24};
final Map<String, dynamic> params = {
"cname": '45',
"uid": '33232',
"clientRequest": value
};
Upvotes: 1
Views: 3330
Reputation: 31209
Your issue is that you are misunderstanding the type system in Dart. There are both type on variables but also type on the object itself you are creating.
In case of Map
this can be a little confusing at first. E.g.:
const Map<String, int> value = {"resourceExpiredHour": 24};
print({
"cname": '45',
"uid": '33232',
"clientRequest": value
}.runtimeType); // _InternalLinkedHashMap<String, Object>
print(<String, dynamic>{
"cname": '45',
"uid": '33232',
"clientRequest": value
}.runtimeType); // _InternalLinkedHashMap<String, dynamic>
As you can see, the type of the Map can either be automatically determined or forced by specifying the type explicit.
In this case, Dart are trying to see what type there are in common with all the different types used as values. In this case this is Object
since String
and Map<String, int>
does not have anything in common other than they are both objects.
Your problem is that the following code is not correct if you have disabled implicit type casting:
final Map<String, dynamic> params = {
"cname": '45',
"uid": '33232',
"clientRequest": value
};
The map defined here will be determined to be Map<String, Object>
but you are forcing it into a variable which can only point to a Map<String, dynamic>
which gives your error.
A possible fix here is to tell the type you actually want when creating the map like:
final Map<String, dynamic> params = <String, dynamic>{
"cname": '45',
"uid": '33232',
"clientRequest": value
};
Or simplify it with this since tr
will automatically be determined to be a variable of the type Map<String, dynamic>
:
final params = <String, dynamic>{
"cname": '45',
"uid": '33232',
"clientRequest": value
};
And to fix your example:
void main() {
const value = {"resourceExpiredHour": 24};
final params = <String, dynamic>{
"cname": '45',
"uid": '33232',
"clientRequest": value
};
print(params); // {cname: 45, uid: 33232, clientRequest: {resourceExpiredHour: 24}}
}
I should properly also add that the dynamic
is really not needed for this specific example since we can also just do (since Map<String, Object>
is a totally fine type for params
):
void main() {
const value = {"resourceExpiredHour": 24};
final params = {
"cname": '45',
"uid": '33232',
"clientRequest": value
};
print(params); // {cname: 45, uid: 33232, clientRequest: {resourceExpiredHour: 24}}
}
Upvotes: 3