1
我有以下代碼,我試圖使用字符串插值來訪問嵌套地圖值。但是,它會返回整個變量而不僅僅是一個特定的值。使用字符串插值訪問dartlang中的嵌套地圖中的值
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]');
}
我該如何解決這個問題?感謝任何見解。
正確。插值可以是'$ identifier'(標識符不能包含任何'$'字符)或'$ {expression}',它可以是任何表達式。 – lrn
另外,如果標識符包含'$','$ identifier'不起作用。在這種情況下,字符串插值嘗試將其讀爲兩個單獨的標識符:'「$ foo $ bar」'將被解釋爲'「$ {foo} $ {bar}」'。如果你的變量被命名爲「foo $ bar」,那麼你需要讚美:''$ {foo $ bar}「'。 –