【问题标题】:How to save data of type bool in shared_preferences flutter如何在 shared_preferences flutter 中保存 bool 类型的数据
【发布时间】:2021-04-21 19:03:04
【问题描述】:

我创建了一个单独的 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


    【解决方案1】:

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

    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
    }
    

    【讨论】:

      猜你喜欢
      • 2021-03-29
      • 1970-01-01
      • 2023-04-11
      • 2021-04-26
      • 2022-11-27
      • 2020-02-28
      • 2022-11-07
      • 2021-12-20
      • 1970-01-01
      相关资源
      最近更新 更多