How to store data locally on Flutter iOS and Android using Shared Preferences?
Subscribe to TLDRStories.com to get your daily dose of tech news, condensed into a few stories.
Shared preferences is one of the many ways to store data locally on iOS and Android devices.
This method is good if you need to save a small set of data locally, like the application setting. This means that if your user has a second mobile device loading into this application they cannot retrieve the same setting because it is saved locally on the first mobile device, but it is still up to how you want the user to experience the application.
For large applications or data sets, I recommend you use a cloud database or sqflite.
Let’s get started
- Add this into pubspec.yaml. This will auto-download the shared preferences package into your project in vscode. Make sure the indentation is correct, incorrect indentation might cause funny errors.
dependencies:
flutter:
sdk: flutter
shared_preferences: 0.5.6+3
2. Import this into your dart file.
import 'package:shared_preferences/shared_preferences.dart';
3. Now you can start saving data by using the set functions. You can set any key(String). You should use a unique key to store different data. If you use the same key, it will overwrite the previous data, that is how you update the same data.
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString(key, data);
4. This is how you get the stored data.
SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.getString(key);
Here is the list of functions you can use.
Set value functions
// Saves a [value] to persistent storage in the background.setBool()
setDouble()
setInt()
setString() // Saves a list of strings to persistent storage in the background.
setStringList()
Get value functions
get() // Reads a value of any type from persistent storage.
getBool() // Reads a value from persistent storage.
getDouble() // Reads a value from persistent storage.
getInt() // Reads a value from persistent storage.
getString() // Reads a value from persistent storage.
getKeys() // Returns all keys in the persistent storage.// Reads a set of string values from persistent storage. getStringList()
Other functions.
// Returns true if persistent storage the contains the given [key].
containsKey()// Completes with true once the user preferences for the app has been cleared.
clear()// Fetches the latest values from the host platform.
reload()// Removes an entry from persistent storage.
remove()
You can populate SharedPreferences
with initial values in your tests by running this code.
SharedPreferences.setMockInitialValues (Map<String, dynamic> values);
You just leveled up in flutter…hahaha! Drop me a comment if you have. That is all!
Subscribe to TLDRStories.com to get your daily dose of tech news, condensed into a few stories.