You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中选择正确答案却返回false的问题排查与解决

问题原因
  1. 状态变量管理错误:randomElement、answers等核心变量被定义在类外部,不属于组件状态,点击Next时会先更新题目内容,导致判断时使用的是新题目而非用户答题时的旧题目。
  2. 判断逻辑顺序颠倒:Next按钮回调中,先执行新题目和选项的生成,再进行答案判断。此时answers已是新选项列表,selectedIndex对应旧选项的索引,两者完全不匹配,必然判断错误。
  3. 全局变量副作用:全局的randomElement会在组件重建或状态更新时被意外覆盖,无法保留用户答题时的正确答案。
解决方法

步骤1:将核心变量移至State类内部作为状态变量

把题目、选项等变量放到_MyHomePageState中,通过setState管理状态,确保数据仅在组件内部维护。

步骤2:调整Next按钮的逻辑顺序

先判断用户当前选择是否正确,再生成新题目和选项,避免旧数据被提前覆盖。

步骤3:优化选项生成逻辑(推荐)

确保正确答案一定会出现在选项中,同时避免重复选项。

修正后的完整代码

class MyHomePage extends StatefulWidget {
  MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final characters = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
  final random = Random();
  
  // 状态变量:当前题目、选项、选中索引
  late String currentQuestion;
  late List<String> options;
  int selectedIndex = -1;

  @override
  void initState() {
    super.initState();
    // 初始化题目和选项
    _generateNewQuestion();
  }

  // 生成新题目和选项的方法
  void _generateNewQuestion() {
    // 生成当前题目
    currentQuestion = characters[random.nextInt(characters.length)];
    // 生成选项:确保包含正确答案,且选项不重复
    Set<String> optionSet = {currentQuestion};
    while(optionSet.length <4){
      optionSet.add(characters[random.nextInt(characters.length)]);
    }
    options = optionSet.toList()..shuffle();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: SingleChildScrollView(
        physics: const ScrollPhysics(),
        child: Column(
          children: [
            Text(
              'Select: $currentQuestion',
              style: const TextStyle(fontSize: 22),
            ),
            ListView.builder(
                physics: const NeverScrollableScrollPhysics(),
                shrinkWrap: true,
                itemCount: options.length,
                itemBuilder: (BuildContext context, int index) {
                  return ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      backgroundColor:
                          selectedIndex == index ? Colors.grey : Colors.white,
                    ),
                    onPressed: () {
                      setState(() {
                        selectedIndex = index;
                      });
                    },
                    child: Text(
                      options[index],
                    ),
                  );
                }),
            ElevatedButton(
              onPressed: () {
                // 先判断当前答案是否正确
                if(selectedIndex != -1){
                  if(currentQuestion == options[selectedIndex]){
                    debugPrint('correct');
                  }else{
                    debugPrint('false');
                  }
                }
                // 生成新题目并重置选中状态
                setState(() {
                  _generateNewQuestion();
                  selectedIndex = -1;
                });
              },
              child: const Text('Next'),
            )
          ],
        ),
      ),
    );
  }
}

关键改进点

  • 所有核心变量封装在State类中,通过initState初始化,_generateNewQuestion统一管理题目生成逻辑。
  • Next按钮先执行答案判断,再生成新题目,确保判断基于用户答题时的旧数据。
  • 使用Set生成选项,避免重复选项,同时保证正确答案必然存在于选项中。

内容的提问来源于stack exchange,提问作者Jorpy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 02:10:33