和NSUserDefault一样,以键值对的形式保存数据到本地
导入框架:
shared_preferences:
引入头文件:
import 'package:shared_preferences/shared_preferences.dart';
创建一个工具类用来管理用户本地数据
UserManager.dart:
import 'package:flutter_webapp/UserModel.dart';
import 'package:shared_preferences/shared_preferences.dart';
class UserManager {
// save
static Future save(String key, String value) async {
SharedPreferences pref = await SharedPreferences.getInstance();
pref.setString(key, value);
}
// get
static Future<String> get(String key) async {
SharedPreferences pref = await SharedPreferences.getInstance();
return pref.getString(key);
}
// delete
static Future delete(String key) async {
SharedPreferences pref = await SharedPreferences.getInstance();
pref.remove(key);
}
// clear
static Future clear() async {
SharedPreferences pref = await SharedPreferences.getInstance();
pref.clear();
}
}
调用:
UserManager.save('userId', myuserId);
网友评论