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

Flutter测验应用调整索引位置后触发StackOverflowError如何解决

问题原因

你遇到的StackOverflowError是QuizBrain类的设计存在递归实例化漏洞导致的:
当前你把「单道题目的属性」和「全局题目列表」都写在了同一个QuizBrain类里,当你创建第一个QuizBrain实例时,类内部的listaIntrebarilor需要初始化4个QuizBrain子实例,这4个子实例又会各自初始化自己内部的listaIntrebarilor,再生成更多QuizBrain实例,无限循环直到栈空间被占满。

解决方案

拆分单题实体和题库管理逻辑,修改如下:

1. 修改QuizBrain.dart代码

// 先定义单道题的实体类,仅存储单题数据
class Intrebare {
  final String text;
  final bool raspunsCorect;

  const Intrebare({required this.text, required this.raspunsCorect});
}

// 题库管理类,仅负责存储题目列表、提供操作方法
class QuizBrain {
  final List<Intrebare> listaIntrebarilor = const [
    Intrebare(text: 'Este sangele rosu?', raspunsCorect: true),
    Intrebare(text: 'Melcul zboara ?', raspunsCorect: false),
    Intrebare(text: '0 + 1 = 3', raspunsCorect: false),
    Intrebare(text: 'Pestele inoata?', raspunsCorect: true),
  ];
}

2. 修改material.dart里的对应调用

只需调整题目读取的字段名即可,同时修正你index自增的错误写法(原来的index = index++是无效赋值,后置++会先返回旧值再自增,赋值后index不会变化):

// Text组件的内容调整为新字段
child: Text(
  Creier.listaIntrebarilor[index].text,
  textAlign: TextAlign.center,
  style: TextStyle( fontSize: 30, color: Colors.white,),
),
// 按钮判断逻辑替换为新字段
bool dilema = Creier.listaIntrebarilor[index].raspunsCorect;
// setState里的自增逻辑修正,可补充边界判断避免数组越界
setState((){
  index++;
  if (index >= Creier.listaIntrebarilor.length) {
    index = 0;
  }
});

修改后重新运行项目即可解决栈溢出问题,无需额外清理缓存。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 19:15:05