Eind997
Eind997

Reputation: 467

How can I randomly order my elements in Flutter/Dart?

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?

Upvotes: 0

Views: 353

Answers (2)

eamirho3ein
eamirho3ein

Reputation: 17950

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()
      ],
    );
  }

Upvotes: 2

OMi Shah
OMi Shah

Reputation: 6186

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()
  ],
)

Upvotes: 1

Related Questions