Home > Mobile >  Access values in nested dictionary in dart
Access values in nested dictionary in dart

Time:03-20

I am basically trying to access a value inside a dictionary that is inside another one.

void main() {
var results = {
  'usd' : {"first": 2, "second": 4},
  'eur' : 4.10, 
  'gbp' : 4.90, 
  };

  print(results['usd']["first"]);

}

The issue is I am facing that I get an error:

Error: The operator '[]' isn't defined for the class 'Object?'.

  • 'Object' is from 'dart:core'.
    print(results['usd']["first"]);

I cannot find the explanation for it, and how to fix it.

Thank you in advance.

CodePudding user response:

The issue arises because your results map has values of different types. Euro and Pound are doubles, but Dollar is a map. So the compiler can't infer a better type for results than Map<String, Object>. You need to give it some help, by telling it the type of type of the usd value.

void main() {
  var results = {
    'usd': {
      'first': 2,
      'second': 4,
    },
    'eur': 4.10,
    'gbp': 4.90,
  };

  final usd = results['usd'] as Map<String, dynamic>;
  print(usd['first']);
}

CodePudding user response:

change the type to Map like:

void main() {
Map results = {
  'usd' : {"first": 2, "second": 4},
  'eur' : 4.10, 
  'gbp' : 4.90, 
  };

  print(results['usd']['first'].toString());

}
  • Related