Flutter开发:如何从题库类中随机抽取5道题目?
Flutter随机抽取5道题的实现方案
核心思路
利用Dart的集合API和随机类,从你的6道题题库中筛选出不重复的5道题,以下是两种简单易上手的实现方式:
1. 先定义你的题库结构(参考)
假设你已经有了Question实体类和完整题库列表:
class Question { final String questionText; final List<String> options; final int correctAnswerIndex; Question({ required this.questionText, required this.options, required this.correctAnswerIndex, }); } // 你的完整6道题题库 final List<Question> allQuestions = [ Question(questionText: "题目1", options: ["A", "B", "C"], correctAnswerIndex: 0), Question(questionText: "题目2", options: ["A", "B", "C"], correctAnswerIndex: 1), // 剩下4道题同理补充... ];
2. 实现随机抽取方法
方式一:打乱列表后取前5道(最简洁)
这种方式代码量少,适合大多数场景:
List<Question> getRandomQuestions() { // 复制原题库列表,避免修改原始数据 final tempQuestions = List.from(allQuestions); // 随机打乱列表顺序 tempQuestions.shuffle(); // 取前5道题返回 return tempQuestions.take(5).toList(); }
方式二:通过随机索引选取(精确控制不重复)
如果需要更灵活的控制(比如后续调整抽取数量),可以用这种方式:
import 'dart:math'; List<Question> getRandomQuestions() { final random = Random(); final selected = <Question>[]; final usedIndices = <int>[]; while (selected.length < 5) { final index = random.nextInt(allQuestions.length); // 确保没选过这道题 if (!usedIndices.contains(index)) { usedIndices.add(index); selected.add(allQuestions[index]); } } return selected; }
3. 在页面中使用
在你的测验页面初始化时调用方法,获取随机题目:
late List<Question> currentQuizQuestions; @override void initState() { super.initState(); // 初始化时加载随机题目 currentQuizQuestions = getRandomQuestions(); }
注意事项
- 必须复制原题库列表再操作,不要直接修改
allQuestions,否则会导致后续抽取的题目混乱 - 如果以后题库题数变化,可把抽取数量改成参数(比如
take(desiredCount)),同时加判断确保desiredCount不超过总题数
内容的提问来源于stack exchange,提问作者Rogers
相关产品推荐
相关产品推荐

