Flutter问答组件点击按钮后问题不更新排查求助
问题分析与修复方案
核心问题
你在chooseAnswer方法里定义了同名的index参数,直接覆盖了类的成员变量index。所以你在setState里修改的只是这个局部参数,类里的index根本没变化,UI自然不会更新。
修复步骤
- 移除方法的
index参数:直接使用类的成员变量index(可省略this.,明确写出更清晰) - 将
index类型改为int:问题索引本来就是整数,用double完全没必要 - 优化
marks类型:指定具体类型,避免动态类型带来的潜在问题 - 移除
setState里的display()调用:setState会触发build,build里会自动调用display(),手动调用毫无意义 - 添加索引边界检查:防止最后一题点击按钮时出现越界错误
修改后的完整代码
class _QuestionQuizState extends State<QuestionQuiz> { late Map<String, bool> _ques; List<String> marks = []; // 指定具体类型,代码更规范 int index = 0; // 改为int类型,符合索引的整数特性 final String t = 'true'; final String f = 'false'; @override void initState() { super.initState(); _ques = widget.questions; } String display() { final questionNo = _ques.keys.elementAt(index).toString(); return questionNo; } void chooseAnswer(String text) { // 移除多余的index参数 final answer = _ques.values.elementAt(index).toString().toLowerCase(); setState(() { // 简化分数添加逻辑 marks.add(answer == text ? '1' : '0'); // 边界检查:避免索引超出问题数量 if (index < _ques.length - 1) { index += 1; } else { // 可在此添加测验结束的逻辑,比如显示总分 print('测验结束!'); } }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('hello'), ), body: Column( children: [ const SizedBox(height: 20), Container( width: MediaQuery.of(context).size.width, height: MediaQuery.of(context).size.height * 0.1, decoration: const BoxDecoration( gradient: LinearGradient( begin: Alignment.topLeft, end: Alignment.bottomRight, colors: [ Colors.black, Colors.brown, ], ), boxShadow: [ BoxShadow( color: Colors.black26, blurRadius: 5.0, offset: Offset(0, 2), ), ], ), child: Center( child: Text( display(), style: const TextStyle( color: Colors.white, fontSize: 18, ), ), ), ), const SizedBox(height: 15), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Container( decoration: const BoxDecoration( gradient: LinearGradient( begin: Alignment.topLeft, end: Alignment.bottomRight, colors: [ Colors.black, Colors.brown, ], ), borderRadius: BorderRadius.all(Radius.circular(20)), boxShadow: [ BoxShadow( color: Colors.black26, blurRadius: 5.0, offset: Offset(0, 2), ), ], ), child: TextButton( onPressed: () { chooseAnswer(t); // 仅传递text参数 }, child: const Text( 'True', style: TextStyle( color: Colors.white, fontSize: 18, ), ), ), ), const SizedBox(width: 20), Container( decoration: const BoxDecoration( gradient: LinearGradient( begin: Alignment.topLeft, end: Alignment.bottomRight, colors: [ Colors.black, Colors.brown, ], ), borderRadius: BorderRadius.all(Radius.circular(20)), boxShadow: [ BoxShadow( color: Colors.black26, blurRadius: 5.0, offset: Offset(0, 2), ), ], ), child: TextButton( onPressed: () { chooseAnswer(f); // 仅传递text参数 }, child: const Text( 'False', style: TextStyle( color: Colors.white, fontSize: 18, ), ), ), ), ], ), const SizedBox(height: 10), DisplayResult( marks: marks, ) ], ), ); } }
内容的提问来源于stack exchange,提问作者Ahmad Maaz
相关产品推荐
相关产品推荐

