我是颤振的新手,你能解释一下颤振中的这些代码吗?
children: [
Question(_questions.elementAt(_questionIndex)['questionText']),
...(_questions.elementAt(_questionIndex)['answers']as List<String>).map((answer) {
return Answer(answerQuestion, answer);
}).toList(),
答案是 dart 文件,它返回一个容器(特定的提升按钮)。顺便说一句,这是此代码中使用的一些术语的定义:
int _questionIndex = 0;
List _questions = [
{
'questionText': 'What is your favorite animal ?',
'answers': ['Cat', 'Dog', 'Fish'],
},
{
'questionText': 'What is your favorite color ?',
'answers': ['Blue', 'Red', 'Yellow', 'Green'],
},
{
'questionText': 'What is your favorite character ?',
'answers': ['A', 'B'],
}
];
这应该创建一个与 _question 列表中的项目数相对应的小部件列表。
但是有一种更好的方法可以做到这一点;通过使用map
:
chidden: _questions.map((element){
Question(element. questionText, element.answers), //If Question() is a Widget
}).toList(),
然后在您的问题小部件中:
class Question extends StatelessWidget{
final String question;
final List<String> answers;
Question(this.question, this.answers);
@override
_QuestionState createState() => _QuestionState();
}
class _QuestionState extends State<Question>{
@override
Widget build(BuildContext context){
return Container(
child: Column(
children: [
Text(question),
SizedBox(height: 10.0),
Column(
children: widget.answers.map((answer){
return ElevatedButton(
child: Text(answer),
onPressed:(){
//Do something when an answer is selected
}
);
}).toList()),
SizedBox(height: 10.0),
),
);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句