Learn how to save simple data types using shared_preferences in Flutter, including strings, integers, booleans, and more. Explore best practices for managing keys and handling errors.
In mobile app development, persisting user data is crucial for maintaining a seamless user experience. Flutter provides several ways to achieve data persistence, and one of the simplest methods is through the shared_preferences
package. This package allows you to store simple data types such as strings, integers, booleans, doubles, and lists of strings in a key-value pair format. This section will guide you through the process of saving simple data using shared_preferences
, highlighting best practices and potential pitfalls.
The shared_preferences
package supports the following data types:
To store data using shared_preferences
, you need to follow these steps:
Add the Dependency: First, ensure that the shared_preferences
package is included in your pubspec.yaml
file:
dependencies:
flutter:
sdk: flutter
shared_preferences: ^2.0.6
Import the Package: Import the shared_preferences
package in your Dart file:
import 'package:shared_preferences/shared_preferences.dart';
Save Data: Use the appropriate set
method to store data. Here are examples for different data types:
Future<void> saveUserName(String username) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setString('username', username);
}
Future<void> saveUserAge(int age) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setInt('user_age', age);
}
Future<void> saveUserLoggedIn(bool isLoggedIn) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setBool('is_logged_in', isLoggedIn);
}
Each method is asynchronous, returning a Future
that completes once the data is saved.
When using shared_preferences
, it’s important to manage keys effectively to avoid conflicts and ensure data integrity:
user_name
instead of name
.profile_user_name
) to prevent collisions.While shared_preferences
is straightforward, it’s essential to handle potential errors gracefully:
Let’s consider a practical example where we save user preferences such as theme settings and login status:
Future<void> saveThemePreference(bool isDarkMode) async {
try {
final prefs = await SharedPreferences.getInstance();
await prefs.setBool('is_dark_mode', isDarkMode);
} catch (e) {
print('Failed to save theme preference: $e');
}
}
Future<void> saveLoginStatus(bool isLoggedIn) async {
try {
final prefs = await SharedPreferences.getInstance();
await prefs.setBool('is_logged_in', isLoggedIn);
} catch (e) {
print('Failed to save login status: $e');
}
}
In this example, we use try-catch blocks to handle any exceptions that might occur during the saving process, ensuring that our app remains robust even in the face of errors.
To better understand the flow of saving data using shared_preferences
, consider the following Mermaid.js diagram:
graph LR A[App] --> B[User Action] B --> C[Call Save Function] C --> D[shared_preferences.setX] D --> E[Data Saved Persistently]
This diagram illustrates the process from user action to data being saved persistently, highlighting the role of shared_preferences
in the data storage workflow.
shared_preferences
is not suitable for large data sets or complex data structures. Use it for simple, lightweight data.shared_preferences
is not encrypted. Avoid storing sensitive information such as passwords or personal data.Using shared_preferences
in Flutter is an effective way to persist simple data types, enhancing the user experience by retaining preferences and states across sessions. By following best practices for key management and error handling, you can ensure that your app remains reliable and user-friendly. As you continue to develop your Flutter applications, consider how shared_preferences
can be integrated to improve data persistence and user satisfaction.
For further exploration, refer to the official shared_preferences documentation and consider experimenting with more complex data persistence solutions as your app’s needs evolve.