skip to Main Content

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?

2

Answers


  1. 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()
          ],
        );
      }
    
    Login or Signup to reply.
  2. 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()
      ],
    )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search