Issue
I'm new to flutter I've Created a nested list with questions and answers like this
var questions = [
{
'question': '1+1',
'answer': [
{'text': 2,'correct':1},
{'text': 3,'correct':0},
{'text': 4,'correct':0},
{'text': 5,'correct':0}
]
},
{
'question': '1+4',
'answer': [
{'text': 2,'correct':0},
{'text': 3,'correct':0},
{'text': 4,'correct':0},
{'text': 5,'correct':1}
]
},
{
'question': '1+7',
'answer': [
{'text': 7,'correct':0},
{'text': 8,'correct':1},
{'text': 9,'correct':0},
{'text': 10,'correct':0}
]
},
];
Now I want to get the value of answer[0] or answer1 and add that value to the RaisedButton text Or even if it's a possibility to use for loop to generate a button for each answer
Thanks in advance.
I've tried
for ( var i in questions ) RaisedButton(onPressed: (){},child: Text((i['answer'].toString())),)
but I get it like this
Solution
Seems like questions
is a List
and that list again contains a List
which is i['answer']
and that contains Map
.
First you have to iterate over List
(below code snippet I used ListView
, if the list is not long you can use for
or map
). Next you have to again iterate because it contains a List
also (for this I used for loop but you can use map()
also). Then to get the question text you can use the key, which is text
:
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: questions.length,
itemBuilder: (BuildContext context, int index) {
final quest = questions[index]['answer'];
return Row(
children: [
for (final q in quest)
RaisedButton(
onPressed: (){
print(q["correct"] == 1);
},
child: Text(q["text"].toString() ?? ""),
)
],
);
}
);
}
Try using dartpad.
Answered By - Blasanka
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.