如何在Flutter/Dart中随机排列元素?

dgiusagp  于 2022-11-30  发布在  Flutter
关注(0)|答案(2)|浏览(218)

我正在尝试随机排序将出现在列中的小部件。

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

我想打乱小部件中启动...(questions[questionIndex]...的部分,但当我这样做时,将.shuffle()添加到列表中,会出现Spread elements in list or set literals must implement 'Iterable'.错误。我也尝试过将打乱操作移到initState方法中,但随后应用程序会构建,但当我运行应用程序时,我在屏幕上看到错误。(NoSuchMethodError: 'shuffle')。有人知道如何随机排列小部件列表吗?

tjrkku2a

tjrkku2a1#

试试这个:

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

plicqrtu2#

使用shuffle方法对列表进行随机化/随机化:

...((questions[questionIndex]['answers'] as List<Map<String, Object>>)..shuffle())
    • 完整代码:**
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()
  ],
)

相关问题