Flutter:首页数据缓存,读取缓存,更新缓存

每次启动APP,都要等接口返回数据后才能渲染页面,接口如果比较慢,数据可能需要过两三秒才能更新,用户体验不是太好。

想要实现首页的常规数据缓存:

1、请求数据并缓存数据,更新页面,

2、下次启动APP,先读取缓存,更新页面

3、在走接口请求更新数据,存储新的数据,更新页面

controller控制器

js 复制代码
  // 分类导航数据
  List<CategoryModel> categoryItems = [];
  // 推荐商品数据
  List<ProductModel> pushProductList = [];
  
  // 读取缓存
  Future<void> _loadCacheData() async{
    // json字符串
    var string_categoryItems= Storage().getString('categoryItems');
    var string_pushProductList = Storage().getString('pushProductList');
    
    // json字符串转map
    categoryItems = string_categoryItems !=""
    ? jsonDecode(string_categoryItems).map<CategoryModel>((item){
      return CategoryModel.fromJson(item);
    }).toList()
        : [];
        
    pushProductList = string_pushProductList !=""
        ? jsonDecode(string_pushProductList).map<ProductModel>((item){
      return ProductModel.fromJson(item);
    }).toList()
        : [];
    // 如果其中任何一项不为空,则更新视图
    if(categoryItems.isNotEmpty || pushProductList.isNotEmpty){
      update(["home"]);
    }
  }

  /*
  * 需要初始化的数据
  * */
  _initData() async{
    // 分类
    categoryItems = await ProductApi.categories();
    // 推荐商品
    pushProductList = await ProductApi.products(ProductsReq());
    // 缓存数据
    Storage().setJson('categoryItems', categoryItems);
    Storage().setJson('pushProductList', pushProductList);
    update(["home"]);
  }
  
  // onInit:1、先执行,获取缓存
  @override
  void onInit() {
    super.onInit();
    _loadCacheData();
  }

  // onReady:2、后执行,更新数据
  @override
  void onReady() {
    super.onReady();
    _initData();
  }
相关推荐
世人万千丶10 小时前
Flutter 框架跨平台鸿蒙开发 - 恐惧清单应用
学习·flutter·华为·开源·harmonyos·鸿蒙
云烟成雨TD10 小时前
Spring AI Alibaba 1.x 系列【6】ReactAgent 同步执行 & 流式执行
java·人工智能·spring
于慨10 小时前
Lambda 表达式、方法引用(Method Reference)语法
java·前端·servlet
swg32132110 小时前
Spring Boot 3.X Oauth2 认证服务与资源服务
java·spring boot·后端
Utopia^10 小时前
Flutter 框架跨平台鸿蒙开发 - 21天挑战
flutter·华为·harmonyos
gelald11 小时前
SpringBoot - 自动配置原理
java·spring boot·后端
殷紫川11 小时前
深入理解 AQS:从架构到实现,解锁 Java 并发编程的核心密钥
java
一轮弯弯的明月11 小时前
贝尔数求集合划分方案总数
java·笔记·蓝桥杯·学习心得
chenjingming66611 小时前
jmeter线程组设置以及串行和并行设置
java·开发语言·jmeter
殷紫川11 小时前
深入拆解 Java volatile:从内存屏障到无锁编程的实战指南
java