我正在嘗試從下面訪問“第二個”:
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>>'.
解決方案是什么?謝謝!
uj5u.com熱心網友回復:
您可能應該再次熟悉Dart (https://api.dart.dev/stable/2.17.0/dart-core/Map-class.htmlMap和https://api.dart.dev/stable/2.17 .0/dart-core/List-class.html)。List
basic_answers是一個List包含Map<String, Object>元素,所以這樣做是basic_answers.answers行不通的,因為List沒有answers. 甚至basic_answers[0].answers不會作業,。因為元素是 type Map<String, Object>。
要訪問 a 中的值,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,然后answers從 this獲取鍵的值Map。由于該值是另一個值,List我們現在可以使用firstWhere( https://api.dart.dev/stable/2.17.0/dart-core/Iterable/firstWhere.htmlMap ) 來查找包含鍵 'second'的第一個元素 ( )
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/475433.html
