Flutter跨平臺移動端開發(fā)丨封裝本地存儲工具類 SharedPreferences

首先在 pubspec.yaml 文件中添加 shared_preferences 引用并 Packages get

dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  shared_preferences: ^0.4.2

然后封裝 SharedPreferences 工具類

import 'package:shared_preferences/shared_preferences.dart';

/**
 * @des SharedPreferences 工具類
 * @author liyongli 20190522
 * */
class SharedPreferencesDataUtils{

  // 保存數(shù)據(jù)
  Future setUserInfo(key, value) async{
    SharedPreferences sp = await SharedPreferences.getInstance();
    sp.setString(key, value);
  }

  // 獲取數(shù)據(jù)
  Future getUserInfo(key) async{
    SharedPreferences sp = await SharedPreferences.getInstance();
    print(sp.get(key));
    return sp.get(key);
  }

  // 清除數(shù)據(jù)
  Future deleteUserInfo(key) async{
    SharedPreferences sp = await SharedPreferences.getInstance();
    sp.remove(key);
  }

}

調(diào)用方式

    SharedPreferencesDataUtils spDataUtils = new SharedPreferencesDataUtils();

    spDataUtils.setUserInfo("name","Flutter Flutter Flutter");
    spDataUtils.setUserInfo("type","Save Save Save");

    print(dataUtils.getUserInfo("name"));
    print(dataUtils.getUserInfo("type"));

運行結(jié)果

    I/flutter (13801): Flutter Flutter Flutter
    I/flutter (13801): Save Save Save

本篇到此完結(jié),更多 Flutter 跨平臺移動端開發(fā) 原創(chuàng)內(nèi)容持續(xù)更新中~

期待您 關(guān)注 / 點贊 / 收藏 向著 大前端工程師 晉級!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容