Chr Chr - 27 days ago 8
Dart Question

Map values is private when called from class instance

My Dart code is giving me this error:

NoSuchMethodError: Class '_InternalLinkedHashMap' has no getter 'myKey'


Here is my code:

Class A{
Map a = {
"myKey": "Dont privatise this value"};
}
Main(){
A b = new A();
print(b.a.myKey); // Error
print(b.a['myKey']); // Error too..
}


I already searched this problem but I don't understand why the compiler doesn't want to give me
myKey
from the map. But I already checked in the Dart console (by print method in the class constructor) and I am sure the key
myKey
is in the map.

Answer Source

In Dart, you cannot access Map values using the dot-notation. It is an error to evaluate b.a.myKey since Maps do not have a myKey getter. However, b.a['myKey'] shouldn't be an error. A quick check in dartpad shows that it will work: https://dartpad.dartlang.org/10cdcbdc3730cfec175174e675320e54