Flutter MCQ答题选项颜色显示逻辑异常修复需求
Flutter MCQ 答题界面选项颜色修复方案
核心修复逻辑
要实现目标效果,需要区分答题状态(是否提交)、用户选中的选项和正确答案三个关键变量,在构建每个选项时动态判断颜色:
- 未提交时:所有选项用默认样式
- 已提交后:
- 正确答案始终显示绿色
- 用户选错时,自己选的选项显示红色,其余非正确选项保持默认
- 用户选对时,仅正确答案显示绿色,其余保持默认
完整修复代码
import 'package:flutter/material.dart'; class MCQScreen extends StatefulWidget { const MCQScreen({super.key}); @override State<MCQScreen> createState() => _MCQScreenState(); } class _MCQScreenState extends State<MCQScreen> { // 示例题目和选项 final String question = "以下哪个是Flutter的状态管理库?"; final List<String> options = ["React", "Redux", "Provider", "Vuex"]; // 正确答案的索引(对应options的下标) final int correctAnswerIndex = 2; // 状态变量 int? selectedOptionIndex; // 用户选中的选项索引 bool isSubmitted = false; // 是否已经提交答案 // 提交答案的方法 void submitAnswer() { setState(() { isSubmitted = true; }); } // 重置答题状态 void resetQuiz() { setState(() { selectedOptionIndex = null; isSubmitted = false; }); } // 判断单个选项的颜色 Color getOptionColor(int index) { if (!isSubmitted) { // 未提交时用默认背景色 return Colors.grey[200]!; } else { if (index == correctAnswerIndex) { // 正确答案始终绿色 return Colors.green[200]!; } else if (index == selectedOptionIndex && selectedOptionIndex != correctAnswerIndex) { // 用户选错的选项显示红色 return Colors.red[200]!; } else { // 其余非正确选项保持默认 return Colors.grey[200]!; } } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text("MCQ 答题")), body: Padding( padding: const EdgeInsets.all(16.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ // 题目 Text( question, style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold), ), const SizedBox(height: 24), // 选项列表 ...options.asMap().entries.map((entry) { int index = entry.key; String optionText = entry.value; return GestureDetector( onTap: !isSubmitted ? () { setState(() { selectedOptionIndex = index; }); } : null, // 提交后禁止点击 child: Container( width: double.infinity, padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16), margin: const EdgeInsets.only(bottom: 12), decoration: BoxDecoration( color: getOptionColor(index), borderRadius: BorderRadius.circular(8), border: Border.all( color: selectedOptionIndex == index && !isSubmitted ? Colors.blue : Colors.transparent, // 未提交时选中的选项加蓝色边框 ), ), child: Text(optionText), ), ); }).toList(), const SizedBox(height: 24), // 提交/重置按钮 Row( children: [ Expanded( child: ElevatedButton( onPressed: isSubmitted ? resetQuiz : submitAnswer, child: Text(isSubmitted ? "重新答题" : "提交答案"), ), ), ], ), ], ), ), ); } }
关键代码解释
- 状态变量定义:
selectedOptionIndex记录用户选中的选项下标,isSubmitted标记是否提交答案,correctAnswerIndex存储正确答案的下标。 - 颜色判断方法
getOptionColor:这是核心逻辑,根据当前状态动态返回颜色:- 未提交时返回默认灰色背景
- 已提交后,优先判断是否是正确答案(显示绿色),再判断是否是用户选错的选项(显示红色),其余返回默认色
- 选项交互控制:提交答案后禁止点击选项,避免重复选择;未提交时选中的选项加蓝色边框区分。
这样就能完全实现你要的效果:
- 答对时:仅正确答案显示绿色,其余保持默认
- 答错时:用户选的选项红色,正确答案绿色,其余默认
- 未提交时:所有选项默认样式,选中的选项有蓝色边框
内容的提问来源于stack exchange,提问作者fluttercoder
相关产品推荐
相关产品推荐

