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();
  }
相关推荐
Via_Neo6 分钟前
JAVA中以2为底的对数表示方式
java·开发语言
野生技术架构师1 小时前
一线大厂Java面试八股文全栈通关手册(含源码级详解)
java·开发语言·面试
廋到被风吹走1 小时前
【AI】Codex 多语言实测:Python/Java/JS/SQL 效果横评
java·人工智能·python
tERS ERTS2 小时前
MySQL中查看表结构
java
坊钰2 小时前
Java 死锁问题及其解决方案
java·开发语言·数据库
于先生吖2 小时前
SpringBoot+MQTT 无人健身房智能管控系统源码实战
java·spring boot·后端
仍然.2 小时前
算法题目---模拟
java·javascript·算法
wefly20172 小时前
纯前端架构深度解析:jsontop.cn,JSON 格式化与全栈开发效率平台
java·前端·python·架构·正则表达式·json·php
louisgeek3 小时前
Flutter autoDispose、keepAlive 和 ref.keepAlive 的区别
flutter
nbwenren3 小时前
node.js内置模块之---crypto 模块
java