M Al
M Al

Reputation: 461

How to save data of type bool in shared_preferences flutter

I created a separate calss page to working with shared preferences from all the different application pages. Save or edit data. I can save String data with ease, but I am facing a problem saving data of type bool. I try to save data of type bool to store the status of the user logged in or not. I searched for solutions for a long time, but couldn't find.

full code:

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;
  }

  
  

}


Can somebody help me to make bool data.

thank you

Upvotes: 0

Views: 106

Answers (1)

Loren.A
Loren.A

Reputation: 5575

Just add a couple methods to your class.

void updateLoggedIn(bool value) {
    _sharedPreferences.setBool('logged_in', value);
}

bool isLoggedIn() => _sharedPreferences.getBool('logged_in') ?? false;

Then on login just run

MyPreferences.instance.updateLoggedIn(true)

And the same thing passing in false on logout.

Then whenever you want to check logged in status just run

if(MyPreferences.instance.isLoggedIn()) {
// whatever needs to happen
}

Upvotes: 1

Related Questions