Hello everyone.
In Flutter apps, it is important to permanently store user settings or app data on the device. This is where SharedPreferences comes into play in Flutter. In this article, you will learn how to include the SharedPreferences package in your Flutter project, how to save and read data, and how to use it in full detail.
What is SharedPreferences in Flutter and what does it do?
SharedPreferences is a package used to permanently store small pieces of data from Flutter on the device, especially ideal for storing information such as user settings and app state. This way, data is not lost every time the app is launched, and previous data is preserved when the user logs into your app or restarts the app.
SharedPreferences is usually used for:
- For storing small data such as username and password,
- For storing settings such as user preferences (theme, language selection),
- For keeping application status information.
How to Include the SharedPreferences Package in Flutter
To start using SharedPreferences in Flutter projects, we first need to include the package in the project. To do this, add the following line to the pubspec.yaml file:
dependencies:
shared_preferences: ^2.5.3
Note: The most current version number at the time of writing is above. This number may have changed while you were uploading. If you want the version numbers to be automatically added to the file during upload, you can also upload with the command line below.
$ flutter pub add shared_preferences
After that, we can now start using the SharedPreferences package!
Saving, Reading and Deleting Data with SharedPreferences
Saving Data
Saving data using SharedPreferences is quite simple. In the example below, we will save the username.
import 'package:shared_preferences/shared_preferences.dart';
void saveUsername() async {
final prefs = await SharedPreferences.getInstance();
await prefs.setString('username', 'flutter_dev');
print("username is saved!");
}
We get the SharedPreferences object with SharedPreferences.getInstance(). When the data type to be saved here is String, we save the username with setString. If you want to save other types of data, methods like setInt, setBool can also be used.
Reading Data
We can use the following code to read the data we saved:
void getUsername() async {
final prefs = await SharedPreferences.getInstance();
String? username = prefs.getString('username');
if (username != null) {
print("Kullanıcı adı: $username");
} else {
print("Kullanıcı adı bulunamadı!");
}
}
Here, we read the username we saved with the getString method and print it to the screen. If no value is found, it will return null.
Updating Data
It is also quite easy to update the saved data. For example, we can change the username. We use the setString method again, but this time we add the new value.
void updateUsername() async {
final prefs = await SharedPreferences.getInstance();
await prefs.setString('username', 'new_flutter_dev');
print("username is updated!");
}
Note: You may have thought of the following here: we also use the set method for update. How does the program know that it will update the existing one? What if it saves a second value?
At this point, the concept of ‘key’, which is the working logic of SharedPreference, comes into play.
SharedPreferences modifies the data corresponding to a specific key. If the same key has been saved before, it is replaced with a new value. If the same key has not been saved before, SharedPreferences adds new data. That is, instead of registering new data, it updates existing data.
For example, in the example above, it worked like this:
Saving New Data: If the key you specified earlier (e.g. ‘username’) does not exist in SharedPreferences, the value saved with setString was added as new data.
Update Existing Data: If the same key already exists in SharedPreferences, setString updated the existing value. This overwrote the old value with the new value.
So, SharedPreferences set methods always store only one value under only one key. Two different values cannot be stored for the same key. If a key has already been stored, the new data replaces the old data.
Deleting Data
We can use the remove method to delete data. In the example below, we delete the saved username:
void deleteUsername() async {
final prefs = await SharedPreferences.getInstance();
await prefs.remove('username');
print("username is deleted!");
}
Clearing All Data
If you want to delete all SharedPreferences data, you can use the clear method:
void clearAllData() async {
final prefs = await SharedPreferences.getInstance();
await prefs.clear();
print("All data is cleared!");
}
Saving User Settings with SharedPreferences
SharedPreferences is very useful for storing information, especially user settings. For example, when a user changes the theme, we can save this preference. Here, of course, the method we will write requires a bool parameter called isDarkMode.
void saveThemePreference(bool isDarkMode) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setBool('isDarkMode', isDarkMode);
print("Dark theme is saved");
}
We can then read it as follows:
void getThemePreference() async {
final prefs = await SharedPreferences.getInstance();
bool isDarkMode = prefs.getBool('isDarkMode') ?? false;
print("Dark mode: $isDarkMode");
}
Working with Data Types
SharedPreferences can store different data types, not only String. Here are some examples:
- setInt: prefs.setInt(‘key’, 123);
- setBool: prefs.setBool(‘key’, true);
- setDouble: prefs.setDouble(‘key’, 3.14);
- setStringList: prefs.setStringList(‘key’, [‘apple’, ‘banana’]);
Similarly, you can use methods like getInt, getBool, getDouble, and getStringList to read data.
Frequently Asked Questions
How Safe is Saving Data with SharedPreferences? SharedPreferences is suitable for small data storage operations. However, for large or sensitive data, more secure solutions should be preferred.
When is SharedPreferences Used in Flutter Applications? SharedPreferences is used to store user settings, theme preferences, session information and small data.
How many days can I store data in SharedPreferences? Data is stored permanently on the device and is only stored until the user manually deletes the data.
Conclusion
Making your data persistent on the device using SharedPreferences in Flutter is very simple and effective. You can use this method to store user information, preferences and app statuses. It is also very easy to read and update SharedPreferences data. In this way, you have learned how to store persistent data in your application using SharedPreferences!
Thank you for reading this far.
Don’t forget to press clap if you like this article and subscribe to be informed about my other content.
Thank you very much.
Selin.