Ad

Access Values In A Nested Map In Dartlang Using String Interpolation

- 1 answer

I have the following code and I am trying to access the nested map values using string interpolation. However, it returns the entire variable rather than just a particular value.

Map<String, Map<String, String>> questionBank = {
  "1": {
    "question": "What is the capital of Canada?",
    "ans1": "Toronto",
    "ans2": "Montreal",
    "ans3": "Ottawa",
    "ans4": "Vancouver"
  },
  "2": {
    "question": "What is the capital of Britain?",
    "ans1": "London",
    "ans2": "Manchester",
    "ans3": "Newcastle",
    "ans4": "Edinburgh"
  }
};

void main() {
    print('Question: $questionBank[1][question]');
}

How do I address this? Grateful for any insights.

Ad

Answer

Apparently, that evaluates to an expression and not just a variable and therefore needs to be enclosed with a parentheses.

print('Question: ${questionBank["1"]["question"]}');
Ad
source: stackoverflow.com
Ad