I'm trying to randomly order widgets that will appear in a column.
Widget build(BuildContext context){ return Column(
children: [
Question(
questions[questionIndex]['singular'],
),
...(questions[questionIndex]['answers'] as List<Map<String, Object>>).map((answer) {
return Answer(() => answerQuestion(answer['score']), answer['text']);
}).toList()
],
);
}
I want to shuffle the part of the widget that starts ...(questions[questionIndex]...
but when I do this bu adding .shuffle()
to the list to get this error Spread elements in list or set literals must implement 'Iterable'.
I've also tried moving the shuffling to an initState method but then the app builds but I see errors on the screen when I run the app. (NoSuchMethodError: 'shuffle'
). Does anyone know how I can order this list of widgets randomly?
CodePudding user response:
Try this:
Widget build(BuildContext context) {
var answers = (questions[questionIndex]['answers'] as List<Map<String, Object>>);
answers.shuffle();
return Column(
children: [
Question(
questions[questionIndex]['singular'],
),
...answers
.map((answer) {
return Answer(() => answerQuestion(answer['score']), answer['text']);
}).toList()
],
);
}
CodePudding user response:
Use the shuffle method to shuffle/randomise the list:
...((questions[questionIndex]['answers'] as List<Map<String, Object>>)..shuffle())
Complete code:
Column(
children: [
Question(
questions[questionIndex]['singular'],
),
...((questions[questionIndex]['answers'] as List<Map<String, Object>>)
..shuffle())
.map((answer) {
return Answer(() => answerQuestion(answer['score']), answer['text']);
}).toList()
],
)