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();
  }
相关推荐
微学AI1 小时前
Rust语言的深度剖析:内存安全与高性能的技术实现操作
java·安全·rust
程序猿小蒜1 小时前
基于springboot的共享汽车管理系统开发与设计
java·开发语言·spring boot·后端·spring·汽车
lsp程序员0101 小时前
使用 Web Workers 提升前端性能:让 JavaScript 不再阻塞 UI
java·前端·javascript·ui
q***46522 小时前
在2023idea中如何创建SpringBoot
java·spring boot·后端
hygge9992 小时前
Spring Boot + MyBatis 整合与 MyBatis 原理全解析
java·开发语言·经验分享·spring boot·后端·mybatis
q***25212 小时前
Spring Boot接收参数的19种方式
java·spring boot·后端
WX-bisheyuange2 小时前
基于Spring Boot的民谣网站的设计与实现
java·spring boot·后端
q***14642 小时前
Spring Boot文件上传
java·spring boot·后端
WX-bisheyuange4 小时前
基于Spring Boot的民宿预定系统的设计与实现
java·spring boot·后端·毕业设计
码界奇点5 小时前
Java设计模式精讲从基础到实战的常见模式解析
java·开发语言·设计模式·java-ee·软件工程