在dartlang中使用字符串插值访问嵌套映射中的值

7
我有以下代码,我试图使用字符串插值访问嵌套映射的值。然而,它返回整个变量而不仅仅是特定的值。
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]');
}

我该如何解决这个问题?非常感谢您的任何见解。

1个回答

12

显然,那不仅仅是一个变量而是一个表达式,因此需要用括号括起来。

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

正确。插值可以是$identifier(其中标识符不能包含任何$字符)或${expression},其中表达式可以是任何表达式。 - lrn
另外,如果标识符包含 $,则 $identifier 将不起作用。在这种情况下,字符串插值会尝试将其读取为两个单独的标识符:"$foo$bar" 会被解释为 "${foo}${bar}"。如果您的变量名为 foo$bar,则需要使用大括号:"${foo$bar}" - Florian Loitsch

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接