Flutter基础问答应用问题:无法累加数组映射的分数
Flutter问答应用分数累加问题修复方案
问题核心
你的分数无法正确累加,根源在于回调函数类型不匹配和分数传递逻辑错误:
_answerQuestion需要接收当前选中答案的score参数,但你传递给Quiz的是() => _answerQuestion(_totalScore),相当于每次都把当前总分传进去,而非选中答案的分数。Quiz和Answer里定义的VoidCallback是无参函数,无法承载分数参数传递。
修复步骤
1. 调整回调函数类型
修改Quiz和Answer的回调定义,适配分数传递需求:
Quiz.dart
import 'package:flutter/material.dart'; import './question.dart'; import './answer.dart'; class Quiz extends StatelessWidget { // 改为接收int参数的函数类型 final Function(int) answerQuestion; final List<Map<String, Object>> questions; final int questionIndex; Quiz({ required this.answerQuestion, required this.questions, required this.questionIndex, }); @override Widget build(BuildContext context) { return Column( children: [ Question( questions[questionIndex]['questionText'] as String, ), ...(questions[questionIndex]['answers'] as List<Map<String, Object>>) .map((answers) { var answerMap = answers as Map<String, Object>; int score = answerMap['score'] as int; return Answer( // 封装带当前答案分数的回调 () => answerQuestion(score), answerMap['text'] as String, answerMap['desc'] as String, score, ); }).toList() ], ); } }
Answer.dart
import 'package:flutter/material.dart'; class Answer extends StatelessWidget { final VoidCallback selectHandler; final String answerText; final String answerDesc; final int scoreCheck; Answer( this.selectHandler, this.answerText, this.answerDesc, this.scoreCheck, ); @override Widget build(BuildContext context) { return OutlinedButton( style: OutlinedButton.styleFrom( primary: Colors.white, tapTargetSize: MaterialTapTargetSize.shrinkWrap, backgroundColor: Colors.teal, shadowColor: Colors.red, elevation: 10, padding: const EdgeInsets.all(10.10), alignment: Alignment.center, shape: const RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(4))), ), onPressed: selectHandler, child: Column( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.spaceAround, crossAxisAlignment: CrossAxisAlignment.center, children: [ Text(answerText, style: TextStyle(fontSize: 16.0, fontWeight: FontWeight.bold), textAlign: TextAlign.center), Text(answerDesc, style: TextStyle(fontSize: 10.0), textAlign: TextAlign.center), Text("${scoreCheck}", style: TextStyle(fontSize: 16.0, fontWeight: FontWeight.bold), textAlign: TextAlign.center), ], ), ); } }
2. 修正Main.dart的回调传递
在MyApp的build方法中,直接传递_answerQuestion函数引用,而非提前调用:
Main.dart
// 替换原Quiz部分代码 Quiz( answerQuestion: _answerQuestion, // 直接传递函数引用 questionIndex: _questionIndex, questions: _questions, )
3. 完善重置逻辑
在_resetQuiz中重置总分,避免二次答题分数累加:
void _resetQuiz() { setState(() { _questionIndex = 0; _totalScore = 0; // 新增该行重置总分 }); }
修复后逻辑说明
- 用户点击答案时,
Answer的selectHandler触发Quiz中封装的带当前答案分数的回调。 - 回调调用
_answerQuestion并传入正确分数,实现总分累加。 - 重置答题时,总分同步清零,保证新一次答题的准确性。
内容的提问来源于stack exchange,提问作者Bharat Katyal
相关产品推荐
相关产品推荐

