'Access values in nested dictionary in dart
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.
Solution 1:[1]
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());
}
Solution 2:[2]
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']);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | tareq albeesh |
| Solution 2 | Richard Heap |
