You need to enable JavaScript to run this app. 如何优化冗余Flutter代码 减少不必要操作并保留原有本地状态持久化效果
优惠活动
大模型
产品
解决方案
定价
更多

如何优化冗余Flutter代码 减少不必要操作并保留原有本地状态持久化效果

代码优化方案

核心优化原则

  • 完全沿用原有的本地存储key命名规则,不修改任何已存储的数据结构,保证旧版本用户的本地数据100%可读取,功能表现与原代码完全一致
  • 移除所有重复的分支判断,通过动态字符串拼接生成存储key,替代硬编码的if逻辑
  • 修正原代码中将异步SharedPreferences操作放在setState内部的时序问题,避免状态不同步
  • 增加数组越界保护,避免_counter索引溢出的异常

优化后代码

_loadDay() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  final savedDay = prefs.getInt('day') ?? 0;
  final currentDayIndex = savedDay - 1;
  // 动态匹配对应天数的存储key
  final savedScore = prefs.getInt('counter$savedDay') ?? 0;

  setState(() {
    _day = savedDay;
    day = currentDayIndex;
    // 初始化数组对应位置,避免索引越界
    if (_counter.length <= currentDayIndex) {
      _counter.addAll(List.filled(currentDayIndex - _counter.length + 1, 0));
    }
    _counter[currentDayIndex] = savedScore;
    _score = savedScore;
  });
}

_loadCounter() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  // 动态生成key,替代所有硬编码if判断
  final storageKey = 'counter$_day';
  final savedScore = prefs.getInt(storageKey) ?? 0;
  final currentDayIndex = _day - 1;

  setState(() {
    if (_counter.length <= currentDayIndex) {
      _counter.addAll(List.filled(currentDayIndex - _counter.length + 1, 0));
    }
    _counter[currentDayIndex] = savedScore;
    _score = savedScore;
  });
}

_incrementCounter() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  final storageKey = 'counter$_day';
  // 读值、自增、回写
  final newScore = (prefs.getInt(storageKey) ?? 0) + 1;
  await prefs.setInt(storageKey, newScore);
  final currentDayIndex = _day - 1;

  setState(() {
    if (_counter.length <= currentDayIndex) {
      _counter.addAll(List.filled(currentDayIndex - _counter.length + 1, 0));
    }
    _counter[currentDayIndex] = newScore;
    _score = newScore;
  });
}

效果说明

  • 代码量缩减80%以上,消除30组重复的if分支逻辑,后续扩展到更多天数时不需要新增分支代码
  • 所有本地持久化逻辑保持不变,完全满足随时恢复运行状态的需求
  • 修正了原代码中在setState内调用异步_loadCounter导致的状态闪烁、数据不同步问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.14 14:45:09