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

Flutter多Google Sheets调用卡顿问题求助

问题分析与解决方案

嘿,我一眼就发现了问题所在——你在getAllSchedule里对列表的操作方式出错了,这直接导致了函数卡住无法继续执行!

核心问题:空列表的索引赋值错误

你初始化了一个空列表:

List<List<Lesson>> schedules = List<List<Lesson>>();

然后在循环里尝试通过索引直接赋值:

schedules[i] = await getChildSchedule(i);

但空列表根本没有i这个位置的元素,这会触发RangeError(索引越界)。因为这是在异步函数中,错误没有被显式捕获,导致函数被阻塞,既不会抛出明显错误,也无法执行后续代码,看起来就像“卡住”了一样。

修正方案

你有两种简单的修复方式:

方案1:使用add方法添加元素(推荐)

把索引赋值改成add,直接向空列表中追加元素:

Future<List<Lesson>> getAllSchedule() async {
  List<List<Lesson>> schedules = []; // 更简洁的空列表初始化写法
  for (int i = 0; i < ChildrenManager.children.length; i++) {
    print('in getAll schedules: $i');
    var childSchedule = await getChildSchedule(i);
    schedules.add(childSchedule); // 用add替代索引赋值
    print('in getAll schedules: got $i child'); // 现在这句话会正常打印了
  }
  print('in getAll schedules: $schedules');
  List<Lesson> schedule = [];
  for (List<Lesson> sc in schedules) {
    schedule.addAll(sc);
  }
  schedule.sort((a, b) {
    int result = a.startTime.compareTo(b.startTime);
    if (result == 0) {
      return a.endTime.compareTo(b.endTime);
    }
    return result;
  });
  return schedule;
}

方案2:初始化时指定列表长度

如果提前知道子项数量,可以初始化一个指定长度的列表,再通过索引赋值:

Future<List<Lesson>> getAllSchedule() async {
  // 初始化一个指定长度的列表,默认填充null
  List<List<Lesson>?> schedules = List.filled(ChildrenManager.children.length, null);
  for (int i = 0; i < ChildrenManager.children.length; i++) {
    print('in getAll schedules: $i');
    schedules[i] = await getChildSchedule(i);
    print('in getAll schedules: got $i child');
  }
  print('in getAll schedules: $schedules');
  List<Lesson> schedule = [];
  // 过滤掉可能的null(理论上不会出现,但更严谨)
  for (var sc in schedules) {
    if (sc != null) schedule.addAll(sc);
  }
  schedule.sort((a, b) {
    int result = a.startTime.compareTo(b.startTime);
    if (result == 0) {
      return a.endTime.compareTo(b.endTime);
    }
    return result;
  });
  return schedule;
}

额外调试建议

为了避免类似“无声卡住”的问题,建议在异步操作中加入try-catch捕获错误,这样能快速定位问题:

for (int i = 0; i < ChildrenManager.children.length; i++) {
  print('in getAll schedules: $i');
  try {
    var childSchedule = await getChildSchedule(i);
    schedules.add(childSchedule);
    print('in getAll schedules: got $i child');
  } catch (e) {
    print('获取第$i个孩子的日程出错:$e');
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:20:18