I want to add elements in a map which is already a value of a key inside another Map. I need to add element inside answers map.
Map myMap = {
'name' : 'Tom',
'answers' : {
1 : 'correct',
2 : 'wrong'
}
}
I have a list of elements and if my condition passes then add that element inside answers map as (element : 'correct') and if it fails then (element : 'wrong').
To add element inside map based on condition below code works absolutely fine.
myMap.addIf(condition, element, 'correct')
myMap.addIf(!condition, element, 'wrong')
But if I use same logic for adding elements inside answers map it is giving below error.
NoSuchMethodError (NoSuchMethodError: Class '_InternalLinkedHashMap<dynamic, dynamic>' has no instance method 'addIf'.
Receiver: _LinkedHashMap len:0
Tried calling: addIf(false, 1, "correct"))
As a alternate solution I write below code and it is working fine. But is there any way to add element in answers map?
Map otherMap = {};
otherMap.addIf(condition, element, 'correct')
//assigning complete map as a value to answers key
myMap['answers'] = otherMap;
CodePudding user response:
You have to add cast
as shown below:
(myMap['answers'] as Map).addIf(condition, element, 'correct')