Icksir
Icksir

Reputation: 127

How to save data in my settings menu in Flutter?

I was wondering how to save data locally in Flutter. I am creating a Settings menu in my app, and I have a draft made of that UI, but I want to save the user's preferences when they close that menu, but I have no idea how to accomplish that.

Do you know some tutorial to do so? I have searched in Youtube, but I have no idea how to search for it. I have only found UI tutorials and I don't want that.

A picture of my UI is (I want to save that boolean option).

enter image description here

I would appreciate any help you could give to me!

Upvotes: 6

Views: 6960

Answers (2)

rasuru
rasuru

Reputation: 451

You should use shared_preferences package. It's very simple and it's for non-critical data like this! Here is an example how to use it:

class SettingsRepository {
  final SharedPreferences preferences;

  SettingsRepositoryImpl(this.preferences);

  Future<int> getDifficulty() {
    return preferences.getInt(Keys.difficulty) ?? 1;
    // this 1 in the end is a default value
  }

  Future setDifficulty(int difficulty) {
    return preferences.setInt(Keys.difficulty, difficulty);
  }
}

To learn more go to https://pub.dev/packages/shared_preferences. I assume you want to call preferences.setBool

Upvotes: 6

Akif
Akif

Reputation: 7640

You can save your boolean option using shared preferences.

  Future<Null> saveOption(bool isSelected) async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setBool('option', isSelected);
   
  }

Then you can get the option from there.

  Future<bool> getOption() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getBool('option');
   
  }

You can read more from here.

Upvotes: 1

Related Questions