We can use map to run a function for each item within the iterable and return a result for each item, consider the following object:
Some questions have 4 answers and some has 3 answers, and we have a widget for an Answer which takes in the answer text and a onPressed function to move into the next question when an answer has been pressed.
We are showing the question using the question index:
and for the answers we will use map.
let's break it down:
the leading ... is the spreading operator, this will just take all of the values of the list out of the list and into the parent list.
we are accessing the question index and using the map for the answers to the given questions.
The map takes in a function that has the value of each iterable as an argument, great now that we have access to each answer in the answer list we can return the Answer widget for each answer.
finally, we are converting the result to the list using toList(), but using the spreading operate to remove the list at the start of the map.
This will make sure the correct number of answers are rendered on the screen, if a question has 4 answers there will be 4 Answer widgets if it has 3 there will be 3 Answer Widgets.
here is the full code:
questions.dart
answer.dart