Flutter本地存儲可以用 shared_preferences ,其會根據不同操作系統進行相對應的存儲。
1. 使用
1.導入
在pubspec.yaml添加
`shared_preferences: ^2.0.13`
2.對SP進行簡單封裝
```d
import 'package:shared_preferences/shared_preferences.dart';
class SpUtils {
SharedPreferences?prefs;
? SpUtils._() {
init();
? }
static SpUtils?_instance;
? static preInit() {
_instance ??=SpUtils._();
? }
static SpUtilsgetInstance() {
_instance ??=SpUtils._();
? ? return _instance!;
? }
void init()async {
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 value) {
prefs!.setStringList(key, value);
? }
clear(String key){
prefs!.remove(key);
? }
clearAll(){
prefs!.clear();
? }
Tget(String key) {
return prefs!.get(key)as T;
? }
}
```
3.使用
在項目初始頁調用
`SpUtils.preInit();`
存
`SpUtils.getInstance().setString('userId', '12345678');`
`SpUtils.getInstance().setDouble('price', 12.88);`
`SpUtils.getInstance().setInt('count', 200);`
`SpUtils.getInstance().setBool('flag', true);`
取
`SpUtils.getInstance().get('userId');`
刪
`SpUtils.getInstance().clearAll();`
`SpUtils.getInstance().clear('userId');`