首页 > 解决方案 > 如何在 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;
  }

  
  

}


有人可以帮我制作布尔数据吗?

谢谢你

标签: flutter

解决方案


只需在您的类中添加几个方法。

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
}

推荐阅读