I have the following code in dart, which decodes a string into a JSON object.

import 'dart:convert';

void main(){
  var stringValue = "{\"last_supported\": \"2.00\", \"current\": \"2.00\"}";
  var newValue = json.decode(stringValue);

  print(newValue["last_supported"]);
}

The above code works fine, but when I change print statement to: print(newValue.last_supported);
It gives me the following exception:
Uncaught TypeError: C.C_JsonCodec.decode$1(...).get$last_supported is not a function

Is it possible to use dot annotation to access properties, and how?


Solution 1: Osama Abdullah

I'm guessing you come from a java-script background.

in dart object keys cannot be accessed through the . dot notation. rather they are accessed like arrays with ['key_name'].

so that's why this line doesn't work

print(newValue.last_supported)

and this one does

print(newValue["last_supported"]);

dot notation in dart only works on class instances, not Map (similar to JavaScript objects). look at the following :

class User {
   final String name;
   final int age;
   // other props;

   User(this.name, this.age);
}

Now when you create a new user object you can access its public attributes with the dot notation

final user = new User("john doe", 20); // the new keyword is optional since Dart v2

// this works
print(user.name);
print(user.age);

// this doesn't work because user is an instance of User class and not a Map.
print(user['name]);
print(user['age]);

For more about the new keyword you can read the v2 release notes here.