首先在 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:
然后封装 SharedPreferences 工具类
import 'package:shared_preferences/shared_preferences.dart'; /** * @des SharedPreferences 工具类 * @author liyongli 20190522 * */ class SharedPreferencesDataUtils{ // 保存数据 Future setUserInfo(key, value) async{ SharedPreferences sp = await SharedPreferences.getInstance(); sp.setString(key, value); } // 获取数据 Future getUserInfo(key) async{ SharedPreferences sp = await SharedPreferences.getInstance(); print(sp.get(key)); return sp.get(key); } // 清除数据 Future deleteUserInfo(key) async{ SharedPreferences sp = await SharedPreferences.getInstance(); sp.remove(key); } }
调用方式
SharedPreferencesDataUtils spDataUtils = new SharedPreferencesDataUtils(); spDataUtils.setUserInfo("name","Flutter Flutter Flutter"); spDataUtils.setUserInfo("type","Save Save Save"); print(dataUtils.getUserInfo("name")); print(dataUtils.getUserInfo("type"));
运行结果
I/flutter (13801): Flutter Flutter Flutter I/flutter (13801): Save Save Save