You need to enable JavaScript to run this app. Flutter调用_addfromInteger、_resetQuiz等方法问题原因排查求助
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 10:54:03