tailor
tailor

Reputation: 443

What will be the name of SharedPreference created in flutter app?

I just new in flutter and coming from android, In android we declare sharedPreference name like

SharedPreferences sp = Activity.this.getSharedPreferences("USER", MODE_PRIVATE);

by this in android USER.xml file was created,

So, what will be the name of sharedPreference in created by flutter app in this example? how i store collection of data in sharedPreference,like USER, HOBBIES TYPES, etc

addIntToSF() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  prefs.setInt('intValue', 123);
}

read data

getIntValuesSF() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  //Return int
  int intValue = prefs.getInt('intValue');
  return intValue;
}

Upvotes: 3

Views: 1458

Answers (1)

enzo
enzo

Reputation: 11531

You can take a look at the source code of the shared_preferences package:

// Line 37
private static final String SHARED_PREFERENCES_NAME = "FlutterSharedPreferences";

// ...

// Line 54
preferences = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);

So the name is simply "FlutterSharedPreferences".

If you want to group entries by a model (e.g. User, HobbieType), you can add a prefix to each key:

addIntToSF() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  
  // Entries related to users
  prefs.setInt('User_intValue', 123);
  prefs.setString('User_strValue', "123");
  prefs.setBool('User_boolValue', true);
  
  // Entries related to hobbie types
  prefs.setInt('HobbieType_intValue', 456);
  prefs.setString('HobbieType_strValue', "456");
  prefs.setBool('HobbieType_boolValue', false);
}

Upvotes: 3

Related Questions