flutter - 如何在 shared_preferences flutter 中保存 bool 类型的数据
问题描述
我创建了一个单独的 calss 页面来处理来自所有不同应用程序页面的共享首选项。保存或编辑数据。我可以轻松保存字符串数据,但我在保存 bool 类型的数据时遇到了问题。我尝试保存 bool 类型的数据来存储用户是否登录的状态。我找了很长时间的解决方案,但没有找到。
完整代码:
import 'package:shared_preferences/shared_preferences.dart';
class MyPreferences {
static const ID = "id";
static const STATE = "state";
static final MyPreferences instance = MyPreferences._internal();
static SharedPreferences _sharedPreferences;
String id = "";
String state = "";
MyPreferences._internal() {}
factory MyPreferences() => instance;
Future<SharedPreferences> get preferences async {
if (_sharedPreferences != null) {
return _sharedPreferences;
} else {
_sharedPreferences = await SharedPreferences.getInstance();
state = _sharedPreferences.getString(STATE);
id = _sharedPreferences.getString(ID);
return _sharedPreferences;
}
}
Future<bool> commit() async {
await _sharedPreferences.setString(STATE, state);
await _sharedPreferences.setString(ID, id);
}
Future<MyPreferences> init() async {
_sharedPreferences = await preferences;
return this;
}
}
有人可以帮我制作布尔数据吗?
谢谢你
解决方案
只需在您的类中添加几个方法。
void updateLoggedIn(bool value) {
_sharedPreferences.setBool('logged_in', value);
}
bool isLoggedIn() => _sharedPreferences.getBool('logged_in') ?? false;
然后在登录时运行
MyPreferences.instance.updateLoggedIn(true)
同样的事情在注销时传入 false 。
然后,每当您想检查登录状态时,只需运行
if(MyPreferences.instance.isLoggedIn()) {
// whatever needs to happen
}
推荐阅读
- amazon-web-services - 推送操作时出错:No definition available (docker-compose.yaml / docker-compose.yml / Dockerfile)
- windows - 文件夹不断重复,原因不明
- c++ - Qt 有类型转换异常
- javascript - 日本日期选择器日历
- ruby - 如何将对象数组保存到ruby中的文件中?
- makefile - 导出带有美元符号的 makefile 变量
- reactjs - 如何使用 React 测试库为 useMutation 编写测试用例?
- c# - 在 Swagger 中生成响应错误 - .netCore Api
- java - 去除双向链表中的头部
- visual-studio-code - 为什么当我使用这个 textMate 时 VSCode 不突出显示任何内容?