2

I have this code:

 class Dev {
     static final config = const {
       'endpoints': const {
         'signIn': '/v1/auth/sign_in',
       },
       'apiBaseUrl': 'localhost:3000'
     };
    }   

Im trying to access to the signIn property in the config variable, when i do config['endpoints'] it access the property correctly, but when i try

var signInEndpoint = config['endpoints']['signIn'];

It doesn't work, same when i try

var endpoints = config['endpoints'];
var signInEndpoint = endpoints['signIn'];

How can i correctly access signIn property in variable?, thanks in advance.

2 Answers 2

1

That is because the endPoints value is an Object not dynamic, try this:

var signInEndpoint = (Dev.config['endpoints'] as dynamic)['signIn'];
Sign up to request clarification or add additional context in comments.

Comments

1

@Juan you tried two approaches know,

  1. var signInEndpoint = config['endpoints']['signIn'];
    

    which can fixed as per @diegoveloper's suggestion

  2. var endpoints = config['endpoints'];
    var signInEndpoint = endpoints['signIn'];
    

    can be fixed like

    Map endpoints = config['endpoints']; //Map<String, String> will be much better
    var signInEndpoint = endpoints['signIn'];
    

Additional information:

I prefer not having dynamic type as it will create runtime errors only (no compile time error with dynamic/Object).

In your case Dev.config is of Map<String, Object>. Object can be casted to anything and it will create runtime errors.

So I changed the Dev class a bit. Please have a look

class Dev {
  static final Map<String, Map<String, String>> config = const {
    'endpoints': const {
      'signIn': '/v1/auth/sign_in',
      'apiBaseUrl': 'localhost:3000'
    },
  };
}
var signInEndpoint = Dev.config['endpoints']['signIn'] //will work

or like this

class Dev {

  static final Map<String, String> endpoints = const {
    'signIn': '/v1/auth/sign_in',
  };
  static final Map<String, String> config = const {
    'baseUrl': 'localhost:3000',
    'other': 'others'
  };
}
var signInEndpoint = Dev.endpoints['signIn']

2 Comments

Thank you very much, this has given me more options to work with, i think i will use the second approach you have given me.
Glad that it helped you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.