APICloud平台即将全面升级至用友开发者中心,请广大用户查看公告,及时进行账户迁移
APP开发平台 > Blog > flutter缓存处理,flutter缓存方案

flutter使用shared_preferences进行缓存管理

第一步:在pub.dev中获取shared_preferences

第二步:在页面中导入shared_preferences

第三步:定义缓存类:

class HiCache {

  SharedPreferences prefs;

  HiCache._() {

    init();

  }


  static HiCache _instance;


  HiCache._pre(SharedPreferences prefs) {

    this.prefs = prefs;

  }


  /// 预初始化,防止在get使用时,sharedPreference还未初始化

  static Future<HiCache> preInstance() async {

    if (_instance == null) {

      var prefs = await SharedPreferences.getInstance();

      _instance = HiCache._pre(prefs);

    }

    return _instance;

  }


  static HiCache getInstance() {

    if (_instance == null) {

      _instance = HiCache._();

    }

    return _instance;

  }


  void init() async {

    if (prefs == null) {

      prefs = await SharedPreferences.getInstance();

    }

  }


  setString(String key, String value) {

    prefs.setString(key, value);

  }


  setDouble(String key, double value) {

    prefs.setDouble(key, value);

  }


  setInt(String key, int value) {

    prefs.setInt(key, value);

  }


  setBool(String key, bool value) {

    prefs.setBool(key, value);

  }


  setStringList(String key, List<String> value) {

    prefs.setStringList(key, value);

  }


  T get<T>(String key) {

    return prefs?.get(key) ?? null;

  }

}


第四步:使用cache

String username = await HiCache.getInstance().get('userName');

————————————————

原文链接:https://blog.csdn.net/xiejunyan666/article/details/119451337


来APICloud移动应用开发平台学习更多免费APP开发知识:app开发 app开发源码下载 app开发视频教程 app制作模板等免费获取。APICloud支持一键网站自动生成app网站转app网站封装app,有网站即可生成自己的app。

 

立即免费在线制作一个APP,新手注册即送开发大礼包

 

提交app定制需求,了解报价和周期:

 

电脑请点击https://app.apicloud.com/index?uzchannel=500

手机请点击https://app.apicloud.com/m/quickaddcustom


高效的App定制平台,标准化、便宜、快!

提交APP定制开发需求