When developing applications in Flutter, it is often necessary to store values persistently in the application; For this, we have many ways, the most complete would be to use a database in SQLite, but, in case we only want to store a few data, such as the user and referent data such as a shopping cart, purchased courses, etc., we can Opt for a simpler approach such as user preferences, which is a package available for Android, iOS, Windows, MacOS and any technology you want to use.
In this article we will introduce this topic to persistently store data using SharedPreferences in Flutter.
What are SharedPreferences?
SharedPreferences is a persistent storage mechanism that allows Flutter apps (on both Android and iOS) to save data in the form of key-value pairs; being persistent means that they are not only in memory, but on disk, stored in non-volatile memory and can be easily consulted and written.
Data is stored in XML in all applications; they are ideal for managing user data such as ID, email, whether you are authenticated and other related data, their implementation and use is very simple.
SharedPreferences API
Como indicamos antes, con los SharedPreferences podemos escribir y leer (además de leer), así que, tenemos métodos para tal fin:
- getKeys(): Returns all stored keys.
- get(String key): Returns the value associated with the specified key.
- getBool(String key): Returns a boolean value associated with the key.
- getInt(String key): Returns an integer value associated with the key.
- getDouble(String key): Returns a decimal value (double) associated with the key.
- getString(String key): Returns a text value (string) associated with the key.
- getStringList(String key): Returns a list of text values associated with the key.
All the methods are the same, but, depending on the type of data you want to store, we have a different method, such as numbers, string, among others; from time to time the methods to write:
- setBool(String key, bool value): Stores a boolean value associated with the key.
- setInt(String key, int value): Stores an integer value associated with the key.
- setDouble(String key, double value): Stores a decimal value associated with the key.
- setString(String key, String value): Stores a text value associated with the key.
- setStringList(String key, List<String> value): Stores a list of text values associated with the key.
Elimination:
- remove(String key): Removes the key-value pair associated with the specified key.
Also, passing a null value in any of the setters is equivalent to calling remove(key).
Practical example
Suppose we have a class Person. Let's see how to save an instance of this class in SharedPreferences:
import 'package:shared_preferences/shared_preferences.dart';
class Person {
final String name;
final int age;
Person(this.name, this.age);
}
void savePersonToSharedPreferences(Person person) async {
final prefs = await SharedPreferences.getInstance();
prefs.setString('person_name', person.name);
prefs.setInt('person_age', person.age);
}
Future<Person?> getPersonFromSharedPreferences() async {
final prefs = await SharedPreferences.getInstance();
final name = prefs.getString('person_name');
final age = prefs.getInt('person_age');
if (name != null && age != null) {
return Person(name, age);
}
return null;
}
We install the package using:
dependencies:
...
shared_preferences: any
The next step is to carry out the previous implementation, in which we can register and obtain user data; before using it anywhere in the application, we must create the instance:
final prefs = await SharedPreferences.getInstance();
Like all operations, they are asynchronous, which is normal in this type of technology where data is obtained from the disk.
Now, with this object, we can set data with the methods mentioned before, for example, a string:
prefs.setString(key, value);
If it is an object, you can store the data in JSON format:
prefs.setString(key, json.encode(value));
Here is a complete example:
save(String key, value) async {
final prefs = await SharedPreferences.getInstance();
prefs.setString(key, json.encode(value));
}
And finally it allows reading the object or another:
get(String key) async {
final prefs = await SharedPreferences.getInstance();
return json.decode(prefs.getString(key));
}
Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter