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

Flutter测验App点击答题选项时动态修改Container背景色的实现咨询

实现方案

你需要将无状态组件改为有状态组件维护答题状态,再根据选中状态动态修改选项样式,完整修改后代码如下:

import 'package:flutter/material.dart';
import '../HomePage.dart';

// 改为StatefulWidget
class UsaTwo extends StatefulWidget {
  @override
  State<UsaTwo> createState() => _UsaTwoState();
}

class _UsaTwoState extends State<UsaTwo> {
  // 配置正确答案的索引,4个选项对应索引0/1/2/3,可根据实际业务修改
  final int correctAnswerIndex = 2;
  // 记录用户选中的答案索引,未选择时为null
  int? selectedAnswerIndex;
  // 计算属性:用户是否已经作答
  bool get hasAnswered => selectedAnswerIndex != null;

  // 封装选项组件,避免代码重复
  Widget _buildAnswerOption(String text, int index) {
    // 动态计算选项样式
    Color bgColor = Colors.white;
    Color borderColor = Colors.grey;
    Color textColor = Colors.grey;
    Widget? rightIcon;

    if (hasAnswered) {
      if (index == correctAnswerIndex) {
        // 正确答案始终显示绿色
        bgColor = Colors.green;
        borderColor = Colors.green;
        textColor = Colors.white;
        rightIcon = const Icon(Icons.check, color: Colors.white, size: 18);
      } else if (index == selectedAnswerIndex) {
        // 用户选错的选项显示红色
        bgColor = Colors.red;
        borderColor = Colors.red;
        textColor = Colors.white;
        rightIcon = const Icon(Icons.close, color: Colors.white, size: 18);
      }
    }

    return GestureDetector(
      onTap: () {
        // 已经作答后不再响应点击
        if (hasAnswered) return;
        setState(() {
          selectedAnswerIndex = index;
        });
      },
      child: Container(
        margin: const EdgeInsets.only(top: 10),
        padding: const EdgeInsets.all(8.0),
        decoration: BoxDecoration(
          color: bgColor,
          border: Border.all(color: borderColor),
          borderRadius: BorderRadius.circular(15),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              text,
              style: TextStyle(color: textColor, fontSize: 16),
            ),
            Container(
              height: 26,
              width: 26,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(50.0),
                border: Border.all(color: borderColor),
              ),
              child: rightIcon,
            ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey,
      appBar: AppBar(
        leading: IconButton(
          icon: const Icon(
            Icons.arrow_back_ios_rounded,
            color: Colors.black,
          ),
          onPressed: () {
            Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => HomePage(),
                ));
          },
        ),
        backgroundColor: Colors.transparent,
        elevation: 0.0,
      ),
      body: Column(
        children: <Widget>[
          Container(
            margin: const EdgeInsets.symmetric(horizontal: 10),
            padding: const EdgeInsets.all(8.0),
            height: 200.0,
            width: double.infinity,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(20),
              color: Colors.white,
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                Text(
                  '1/10',
                  style: TextStyle(
                      color: Colors.grey[800],
                      fontWeight: FontWeight.bold,
                      fontSize: 20),
                ),
                const SizedBox(height: 10),
                Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Expanded(
                      child: SingleChildScrollView(
                        scrollDirection: Axis.vertical,
                        child: Text(
                          'Question iehfueufbueo bfe bfue bfbuhfih fbeh bfehf bfuwe bfueh fbueh fbeu bfuebi eefojbeb',
                          maxLines: 5,
                          style: const TextStyle(
                              color: Colors.black87,
                              fontWeight: FontWeight.bold,
                              fontSize: 20),
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
          const SizedBox(height: 20),
          Expanded(
            child: Container(
              margin: const EdgeInsets.only(bottom: 10),
              padding: const EdgeInsets.all(8.0),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(25.0),
              ),
              child: Column(
                children: [
                  const SizedBox(height: 10),
                  // 调用封装的选项组件,传入对应参数
                  _buildAnswerOption('Answer 1', 0),
                  const SizedBox(height: 10),
                  _buildAnswerOption('Answer 2', 1),
                  const SizedBox(height: 10),
                  _buildAnswerOption('Answer 3', 2),
                  const SizedBox(height: 10),
                  _buildAnswerOption('Answer 4', 3),
                  const SizedBox(height: 20),
                  Expanded(
                    child: SizedBox(
                      height: 100,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: <Widget>[
                          Directionality(
                            textDirection: TextDirection.ltr,
                            child: Center(
                              child: ElevatedButton.icon(
                                onPressed: () {},
                                style: ElevatedButton.styleFrom(
                                  backgroundColor: Colors.blueAccent,
                                  shape: RoundedRectangleBorder(
                                      borderRadius:
                                          BorderRadius.circular(20.0)),
                                ),
                                icon: const Icon(
                                    Icons.arrow_back_ios_rounded,
                                    color: Colors.white),
                                label: const Text(
                                  'Back',
                                  style: TextStyle(
                                      color: Colors.white, fontSize: 20),
                                ),
                              ),
                            ),
                          ),
                          Directionality(
                            textDirection: TextDirection.rtl,
                            child: Center(
                              child: ElevatedButton.icon(
                                onPressed: () {
                                  // 点击下一题时可重置selectedAnswerIndex为null,加载新题目后刷新状态即可
                                },
                                style: ElevatedButton.styleFrom(
                                  backgroundColor: Colors.blueAccent,
                                  shape: RoundedRectangleBorder(
                                      borderRadius:
                                          BorderRadius.circular(20.0)),
                                ),
                                icon: const Icon(
                                    Icons.arrow_back_ios_rounded,
                                    color: Colors.white),
                                label: const Text('Next',
                                    style: TextStyle(
                                        color: Colors.white, fontSize: 20)),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}

调整说明

  • 只需修改correctAnswerIndex的值即可对应当前题目的正确选项索引
  • 已默认加了对错图标,不需要可以删除rightIcon相关代码
  • 点击下一题时将selectedAnswerIndex重置为null即可重置选项状态,加载下一题内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 12:45:02