When building a mobile application, sooner or later, you come across a situation where you need to store your app’s settings or preferences and retrieve them when you need even after the app is restarted. The main advantage of using this technique is that the data you store remains intact even if the app is closed.
If you are building an app using native codebase(Java/Kotlin for Android or Swift/Objective-C for iOS), you will most probably be using Shared preferences(Android) or NSUserDefaults(iOS).
When it comes to Flutter, it’s quite easy and straightforward to achieve this functionality. Flutter provides you a package called shared_preferences that behind the scene, uses Shared preferences on Android and NSUserDefaults on iOS. It stores data in the form of key-value pairs.
Here is how you can install and use this package:
Install the Package
In the pubspec.yaml file of your project’s root directory, add the following line:
Next, run the following command to install the newly added dependency:
$ flutter packages get
Start using Shared preferences
Import the Shared preferences package in your dart file like this:
Now, wherever you need to save any key-value pair, you can save like this:
SharedPreferences myPrefs = await SharedPreferences.getInstance();myPrefs.setInt('age',20);
One important thing to note is that the above code should be written in an async method because getting shared preferences object takes a little while.
SharedPreferences myPrefs = await SharedPreferences.getInstance();final String name = myPrefs.getString('name');
final int age = myPrefs.getInt('age');
final bool syncData = myPrefs.getBool('syncData');
Note, the keys used to save and retrieve the data should be the same.