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();
  }
相关推荐
forestsea17 分钟前
Maven 插件扩展点与自定义生命周期
java·maven
keke101 小时前
Java【14_2】接口(Comparable和Comparator)、内部类
java·开发语言
CN.LG1 小时前
Java 乘号来重复字符串的功能
java·开发语言
萌新下岸多多关照1 小时前
Java中synchronized 关键字
java·开发语言
中国lanwp1 小时前
使用Maven部署WebLogic应用
java·maven
开开心心就好2 小时前
Word图片格式调整与转换工具
java·javascript·spring·eclipse·pdf·word·excel
CGG922 小时前
【单例模式】
android·java·单例模式
苦学编程的谢2 小时前
多线程代码案例-1 单例模式
java·开发语言·单例模式
yaoxin5211232 小时前
80. Java 枚举类 - 使用枚举实现单例模式
java·开发语言·单例模式
夏季疯3 小时前
学习笔记:黑马程序员JavaWeb开发教程(2025.4.7)
java·笔记·学习