在颤振中随机播放问题

时间:2021-05-29 16:47:54

标签: flutter dart

有谁知道如何在测验中随机排列问题,我正在尝试使用 generate 制作问题列表,但是当我尝试使用 shuffle() 方法时,它给出了错误。

这是一个例子:

class Question {
  final int id, answer;
  final String question;
  final List<String> options;

  Question({this.id, this.question, this.answer, this.options});
}

const List sample_data = [
  {
    "id": 1,
    "question":
        "Flutter is an open-source UI software development kit created by ______",
    "options": ['Apple', 'Google', 'Facebook', 'Microsoft'],
    "answer_index": 1,
  },
  {
    "id": 2,
    "question": "When google release Flutter.",
    "options": ['Jun 2017', 'Jun 2017', 'May 2017', 'May 2018'],
    "answer_index": 2,
  },
  {
    "id": 3,
    "question": "A memory location that holds a single letter or number.",
    "options": ['Double', 'Int', 'Char', 'Word'],
    "answer_index": 2,
  },
  {
    "id": 4,
    "question": "What command do you use to output data to the screen?",
    "options": ['Cin', 'Count>>', 'Cout', 'Output>>'],
    "answer_index": 2,
  },
];

我每 4 个选项创建一个新按钮,当我运行它时,选项永远不会改变它的位置,所以我想改变选项的位置。

按钮是如何制作的:

SizedBox(height: kDefaultPadding),
            ...List.generate(
              question.options.length,
              (index) => Option(
                index: index,
                text: question.options[index],
                press: () => _controller.checkAns(question, index),
              ),
            ),

1 个答案:

答案 0 :(得分:1)

从您调用 shuffle() 的位置或得到什么错误的问题中不清楚,但以下内容可能仍然有用。

如果您有一个如上定义的类 Question,以及一个类 Quiz 定义为:

class Quiz {
  final List<Question> questions;
  Quiz(this.questions);
}

您可以生成一个 Quiz,其中包含 Question 的随机列表,如下所示:

const questions = [ ... ];  // create some questions
final shuffledQuestions = List.from(questions)..shuffle();
final quiz = Quiz(shuffledQuestions);

这里需要注意的一些事情:

  • 我们无法调用 questions.shuffle()questionsconst 意味着它是一个编译时常量,在程序的生命周期内永远不会改变。 shuffle() 修改它被调用的列表,而不是创建一个新的、无序的列表实例。如果您尝试调用 question.shuffle(),您将收到 Unsupported operation 错误。

  • 由于 shuffle() 返回 void,如果我们写 final shuffled = questions.shuffle();shuffled 的类型将是 void(这意味着它不能被使用任何地方)。相反,我们使用 ..(“级联”运算符)。这基本上与以下内容相同:

const questions = ...;
final shuffled = List.from(questions);
shuffled.shuffle();
final quiz = Quiz(shuffled);

还有一点要注意: 不要在 build() 方法中随机排列您的列表。 build() 可以由框架随时调用(可能屏幕改变了方向,可能出现了键盘等),这意味着您的列表将再次被打乱,您的按钮将四处跳跃。< /p>

相反,将数据的创建和改组移到 StateinitState() 方法中。无论重建如何,这保证只被调用一次,您的小部件“停留在同一个地方”