ufk ufk - 3 months ago 11
Dart Question

how to get values from a const object?

I created a const object at app.config.dart with the following code:

const configObj = const {
'webServer': const {
'appBaseHref' : "/"
},
'auth0': const {
'apiKey': "foo",
'domain': "bar",
'callbackUrl': "callback"
}
};


now in my main dart file I import the
app.config.dart
and I try to get the values there and now idea how to do that.
configObj.auth0.apiKey
produces the error
EXCEPTION: Class 'ImmutableMap' has no instance getter 'auth0'
.

so how do I do this ?

thanks!

Answer

Dart doesn't support to access map entries with .

It should be:

configObj['auth0']['apiKey'];

Alternatively you can create classes for your configuration like

class WebServerConfig {
  final String appBaseHref;
  const WebServerConfig(this.appBaseHref);
}

class Auth0Config {
  final String apiKey;
  final String domain;
  final String callbackUrl;
  const Auth0(this.apiKey, this.domain, this.callbackUrl);
}

class MyConfig {
  final WebServerConfig webServer;
  final Auth0Config auth0;
  const MyConfig(this.webServer, this.auth0);      
}

const configObj = const MyConfig(
  const WebServerConfig("/"),
  const Auth0Config(
    "foo",
    "bar",
    "callback"
  )
);

This way you also get proper auto-completion when you access the config properties and can use the simple . notation to access properties.

Comments