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();
  }
相关推荐
Utopia^4 小时前
鸿蒙flutter第三方库适配 - 联系人备份工具
flutter·华为·harmonyos
HoneyMoose4 小时前
Jenkins Cloudflare 部署提示错误
java·servlet·jenkins
阿丰资源4 小时前
基于SpringBoot的物流信息管理系统设计与实现(附资料)
java·spring boot·后端
Predestination王瀞潞4 小时前
Java EE3-我独自整合(第四章:Spring bean标签的常见配置)
java·spring·java-ee
overmind4 小时前
oeasy Python 121[专业选修]列表_多维列表运算_列表相加_列表相乘
java·windows·python
资深数据库专家4 小时前
总账EBS 应用服务器1 的监控分析
java·网络·数据库
房开民4 小时前
可变参数模板
java·开发语言·算法
t***5444 小时前
如何在现代C++中更有效地应用这些模式
java·开发语言·c++
_深海凉_4 小时前
LeetCode热题100-最小栈
java·数据结构·leetcode
不知名的忻5 小时前
Morris遍历(力扣第99题)
java·算法·leetcode·morris遍历