Flutter:getter 'answers' 没有为 class 'List<Map<String, Object>>' 定义
Flutter: The getter 'answers' isn't defined for the class 'List<Map<String, Object>>'
我正在尝试从下面访问 'second':
final basic_answers = const [
{
'questionText': 'Q1. Who created Flutter?',
'answers': [
{'first': 'Facebook', 'score': -2},
{'second': 'Adobe', 'score': -2},
{'third': 'Google', 'score': 10},
{'fourth': 'Microsoft', 'score': -2},
],
},
];
使用这个:
print(basic_answers.answers.second);
但是它给出了以下错误:
Flutter: The getter 'answers' isn't defined for the class 'List<Map<String, Object>>'.
解决这个问题的方法是什么?谢谢!
您可能应该再次熟悉 Dart (https://api.dart.dev/stable/2.17.0/dart-core/Map-class.html and https://api.dart.dev/stable/2.17.0/dart-core/List-class.html) 中的 Map
和 List
。
basic_answers
是一个包含 Map<String, Object>
元素的 List
,所以 basic_answers.answers
将不起作用,因为 List
没有 getter answers
。连basic_answers[0].answers
都不行,。因为元素的类型是 Map<String, Object>
.
要访问 Map
中的值,您可以使用 []
运算符 (https://api.dart.dev/stable/2.17.0/dart-core/Map/operator_get.html),例如 basic_answers[0]['answers']
访问 List
答案。 List
中的元素也是 Map<String, Object>
类型,因此直接访问 second
也不起作用。一种选择是做类似的事情:
print((basic_answers[0]['answers'] as List).firstWhere((el) => el.containsKey('second')));
这会获取 List
的第一个元素,然后从 Map
中获取键 answers
的值。由于值是另一个 List
我们现在可以使用 firstWhere
(https://api.dart.dev/stable/2.17.0/dart-core/Iterable/firstWhere.html) 找到包含键 'second'[=37 的第一个元素 (Map
) =]
我正在尝试从下面访问 'second':
final basic_answers = const [
{
'questionText': 'Q1. Who created Flutter?',
'answers': [
{'first': 'Facebook', 'score': -2},
{'second': 'Adobe', 'score': -2},
{'third': 'Google', 'score': 10},
{'fourth': 'Microsoft', 'score': -2},
],
},
];
使用这个:
print(basic_answers.answers.second);
但是它给出了以下错误:
Flutter: The getter 'answers' isn't defined for the class 'List<Map<String, Object>>'.
解决这个问题的方法是什么?谢谢!
您可能应该再次熟悉 Dart (https://api.dart.dev/stable/2.17.0/dart-core/Map-class.html and https://api.dart.dev/stable/2.17.0/dart-core/List-class.html) 中的 Map
和 List
。
basic_answers
是一个包含 Map<String, Object>
元素的 List
,所以 basic_answers.answers
将不起作用,因为 List
没有 getter answers
。连basic_answers[0].answers
都不行,。因为元素的类型是 Map<String, Object>
.
要访问 Map
中的值,您可以使用 []
运算符 (https://api.dart.dev/stable/2.17.0/dart-core/Map/operator_get.html),例如 basic_answers[0]['answers']
访问 List
答案。 List
中的元素也是 Map<String, Object>
类型,因此直接访问 second
也不起作用。一种选择是做类似的事情:
print((basic_answers[0]['answers'] as List).firstWhere((el) => el.containsKey('second')));
这会获取 List
的第一个元素,然后从 Map
中获取键 answers
的值。由于值是另一个 List
我们现在可以使用 firstWhere
(https://api.dart.dev/stable/2.17.0/dart-core/Iterable/firstWhere.html) 找到包含键 'second'[=37 的第一个元素 (Map
) =]