Flutter调用_addfromInteger、_resetQuiz等方法问题原因排查求助
Flutter调用
_addfromInteger方法问题核心原因定位 你提供的相关业务代码如下:
void _resetQuiz() { setState(() { _questionIndex = 0; _totalScore = 0; }); } void answerQuestion(score) { _totalScore += score; setState(() { _questionIndex += 1; }); print(_questionIndex); print(_totalScore); print("Answer chosen !%n"); }
结合你调用_addfromInteger方法的场景,核心问题原因如下:
- 类型不匹配:
answerQuestion方法的入参score未声明类型,默认为dynamic类型,如果_totalScore被定义为int类型,传入非int类型的score会触发运行时类型异常,此时调用要求整数入参的_addfromInteger方法会直接报错。 - 私有方法访问异常:
_addfromInteger以下划线开头属于Dart语法中的私有方法,仅支持在定义该方法的Dart文件内部调用,如果你是跨文件调用该方法,或是当前类、父类中没有实现该方法,会触发方法未找到的运行时错误。 - 空安全拦截:如果
_questionIndex、_totalScore两个变量未做初始化赋值,也没有标记为可空类型(int?),Dart空安全机制会直接抛出空值访问错误,阻断后续_addfromInteger方法的调用逻辑。
内容的提问来源于stack exchange,提问作者Sa_IS
相关产品推荐
相关产品推荐

