我正在使用 flutter / dart ,并且遇到了以下问题。
我有一个这样的地图列表。
var questions = [
{
'questionText': 'What\'s your favorite color?',
'answer': ['Black', 'Red', 'Green', 'White']
},
{
'questionText': 'What\'s your favorite animal?',
'answer': ['Deer', 'Tiger', 'Lion', 'Bear']
},
{
'questionText': 'What\'s your favorite movie?',
'answer': ['Die Hard', 'Due Date', 'Deep Rising', 'Dead or Alive']
},
];
现在假设我需要从此列表中获取字符串Tiger
。我怎么做? Dart将其视为List<Map<String, Object>> questions
答案 0 :(得分:1)
您可以按照以下方式转换列表中的对象,然后使用索引获取任何值。
var p = questions[1]['answer'] as List<String>;
print(p[1]);
答案 1 :(得分:1)
也许带有功能的更便携的方式:
String getAnswer(int question, int answer) {
return (questions[question]['answer'] as List<String>)[answer];
}
// Get 'Tiger'
String a = getAnswer(1, 1);