Using Local Storage
1. Using shared_preferences Package
| Property | Description | Example |
|---|---|---|
| SharedPreferences.getInstance() | Gets the default instance of SharedPreferences | final prefs = await SharedPreferences.getInstance(); |
| prefs.setString(key, value) | Saves a string value | await prefs.setString('username', 'john_doe'); |
| prefs.getString(key) | Retrieves a string value | String? username = prefs.getString('username'); |
| prefs.setInt(key, value) | Saves an integer value | await prefs.setInt('age', 25); |
| prefs.getInt(key) | Retrieves an integer value | int? age = prefs.getInt('age'); |
| prefs.setBool(key, value) | Saves a boolean value | await prefs.setBool('isDarkMode', true); |
| prefs.getBool(key) | Retrieves a boolean value | bool? isDarkMode = prefs.getBool('isDarkMode'); |
| prefs.remove(key) | Removes a key-value pair | await prefs.remove('username'); |
Example: Saving and Retrieving User Preferences
import 'package:shared_preferences/shared_preferences.dart';
class UserPreferences {
static Future<void> saveUsername(String username) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setString('username', username);
}
static Future<String?> getUsername() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getString('username');
}
}
Note: SharedPreferences is not suitable for large data or sensitive information. It's best used for small key-value pairs like user preferences or settings.
2. Storing Primitive Values
| Method | Description | Example |
|---|---|---|
| setString() | Stores a string value | await SharedPreferences.setKey("username", "JohnDoe"); |
| setInt() | Stores an integer value | await SharedPreferences.setKey("age", 30); |
| setDouble() | Stores a double value | await SharedPreferences.setKey("height", 5.9); |
| setBool() | Stores a boolean value | await SharedPreferences.setKey("isSubscribed", true); |
Note: All values are stored as key-value pairs in a persistent storage mechanism provided by the platform (e.g.,
NSUserDefaults on iOS or SharedPreferences on Android).3. Retrieving Stored Values
| Method | Description | Return Type | Notes |
|---|---|---|---|
| SharedPreferences.getString(key) | Retrieves a string value from shared preferences | String? |
Null if key not found |
| SharedPreferences.getInt(key) | Retrieves an integer value from shared preferences | int? |
Null if key not found |
| SharedPreferences.getDouble(key) | Retrieves a double value from shared preferences | double? |
Null if key not found |
| SharedPreferences.getBool(key) | Retrieves a boolean value from shared preferences | bool? |
Null if key not found |
| SharedPreferences.getStringList(key) | Retrieves a list of strings from shared preferences | List<String>? |
Null if key not found |
Example: Retrieving Values
import 'package:shared_preferences/shared_preferences.dart';
Future<void> retrieveValues() async {
final prefs = await SharedPreferences.getInstance();
String? name = prefs.getString('name');
int? age = prefs.getInt('age');
double? height = prefs.getDouble('height');
bool? isStudent = prefs.getBool('isStudent');
List<String>? hobbies = prefs.getStringList('hobbies');
print('Name: $name');
print('Age: $age');
print('Height: $height');
print('Is Student: $isStudent');
print('Hobbies: $hobbies');
}
Note: All retrieval methods return
null if the key does not exist. Always check for null values before using them.
Warning:
SharedPreferences is not suitable for storing sensitive data like passwords or tokens. Use flutter_secure_storage for such cases.
4. Storing Lists
Storing lists in Flutter typically involves serializing the list to a string format (like JSON) and then saving it to local storage. The following example demonstrates how to store and retrieve a list of strings using shared_preferences.
Example: Storing and Retrieving a List of Strings
// Saving a list of strings
List<String> items = ["item1", "item2", "item3"];
String itemsJson = jsonEncode(items);
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString("savedItems", itemsJson);
// Retrieving the list of strings
String? itemsJson = prefs.getString("savedItems");
List<String> retrievedItems = [];
if (itemsJson != null) {
retrievedItems = jsonDecode(itemsJson);
}
| Method | Description | Notes |
|---|---|---|
| setStringList(key, values) | Sets a list of strings to shared preferences | Available in Flutter 3.10+ |
| getStringList(key) | Retrieves a list of strings from shared preferences | Available in Flutter 3.10+ |
Note: The
setStringList and getStringList methods are available starting from Flutter 3.10, providing a more direct way to handle lists without manual JSON serialization.
5. Removing Stored Values
| Method | Description | Notes |
|---|---|---|
| remove(key) | Removes the value associated with the given key from storage. | Does not throw if key does not exist |
| clear() | Removes all stored key-value pairs from storage. | Deletes all entries in the storage |
Example: Removing Stored Values
import 'package:shared_preferences/shared_preferences.dart';
Future<void> removeStoredValue() async {
final prefs = await SharedPreferences.getInstance();
await prefs.remove('username'); // Removes the 'username' key
await prefs.clear(); // Clears all stored values
}
6. Checking Key Existence
| Method | Description | Return Type | Notes |
|---|---|---|---|
| SharedPreferences.getInstance() | Asynchronously initializes and returns the SharedPreferences instance. | Future<SharedPreferences> |
Must be awaited before using other methods. |
| prefs.containsKey(key) | Checks if a key exists in the SharedPreferences instance. | bool |
Returns true if key exists, otherwise false. |
Example: Checking Key Existence
import 'package:shared_preferences/shared_preferences.dart';
Future<void> checkKeyExistence() async {
final prefs = await SharedPreferences.getInstance();
bool hasToken = prefs.containsKey('auth_token');
if (hasToken) {
print('Token exists');
} else {
print('No token found');
}
}
7. Getting All Keys
| Method | Description | Return Type | Notes |
|---|---|---|---|
| getAllKeys() | Retrieves all keys stored in local storage | Future<List<String>> |
Throws an exception if storage is not available |
Example: Getting All Keys
import 'package:shared_preferences/shared_preferences.dart';
Future<List<String>> getAllKeysExample() async {
final prefs = await SharedPreferences.getInstance();
final keys = prefs.getKeys();
return keys.toList();
}
Note: The
getKeys() method returns a Set<String>, so it must be converted to a list for use in the example.
8. Using SharedPreferences Instance
| Method | Description | Return Type | Notes |
|---|---|---|---|
| getInstance() | Gets the singleton instance of SharedPreferences | Future<SharedPreferences> |
Must be awaited |
| getString(key) | Gets a string value for the given key | String? |
Returns null if key not found |
| getInt(key) | Gets an integer value for the given key | int? |
Returns null if key not found |
| getDouble(key) | Gets a double value for the given key | double? |
Returns null if key not found |
| getBool(key) | Gets a boolean value for the given key | bool? |
Returns null if key not found |
| getStringList(key) | Gets a list of strings for the given key | List<String>? |
Returns null if key not found |
| setString(key, value) | Sets a string value for the given key | Future<void> |
Async operation |
| setInt(key, value) | Sets an integer value for the given key | Future<void> |
Async operation |
| setDouble(key, value) | Sets a double value for the given key | Future<void> |
Async operation |
| setBool(key, value) | Sets a boolean value for the given key | Future<void> |
Async operation |
| setStringList(key, value) | Sets a list of strings for the given key | Future<void> |
Async operation |
| remove(key) | Removes the key-value pair for the given key | Future<void> |
Async operation |
| clear() | Removes all key-value pairs | Future<void> |
Async operation |
Example: Initializing and Using SharedPreferences
import 'package:shared_preferences/shared_preferences.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
final prefs = await SharedPreferences.getInstance();
// Set values
await prefs.setString('name', 'John Doe');
await prefs.setInt('age', 30);
await prefs.setBool('isOnline', true);
// Get values
final name = prefs.getString('name');
final age = prefs.getInt('age');
final isOnline = prefs.getBool('isOnline');
print("Name: $name, Age: $age, Online: $isOnline");
}
Note: SharedPreferences is not suitable for large data or sensitive information. It's designed for small key-value pairs.
9. Storing App Settings and User Preferences
| Property | Type | Description | Default |
|---|---|---|---|
| key | String |
Unique identifier for the setting | null |
| value | dynamic |
The value to store (must be JSON serializable) | null |
Example: Saving User Preferences
import 'package:shared_preferences/shared_preferences.dart';
Future<void> saveUserPreference(String key, dynamic value) async {
final prefs = await SharedPreferences.getInstance();
if (value is String) {
await prefs.setString(key, value);
} else if (value is int) {
await prefs.setInt(key, value);
} else if (value is bool) {
await prefs.setBool(key, value);
} else if (value is double) {
await prefs.setDouble(key, value);
} else if (value is List<String>) {
await prefs.setStringList(key, value);
}
}
Example: Loading User Preferences
Future<String?> getUserPreference(String key) async {
final prefs = await SharedPreferences.getInstance();
return prefs.getString(key);
}
Future<bool> getUserPreferenceBool(String key, {bool defaultValue = false}) async {
final prefs = await SharedPreferences.getInstance();
return prefs.getBool(key) ?? defaultValue;
}
Note:
shared_preferences is a cross-platform solution that stores data in a key-value format. It's ideal for simple settings and preferences but not suitable for large datasets or complex data structures.
10. Implementing Persistent State
Example: Using SharedPreferences for Local Storage
// Save data to local storage
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('username', 'john_doe');
prefs.setInt('user_id', 12345);
// Retrieve data from local storage
String? username = prefs.getString('username');
int? userId = prefs.getInt('user_id');
| Method | Description | Return Type |
|---|---|---|
| getString(key) | Retrieves a string value for the given key | String? |
| getInt(key) | Retrieves an integer value for the given key | int? |
| getDouble(key) | Retrieves a double value for the given key | double? |
| getBool(key) | Retrieves a boolean value for the given key | bool? |
| getStringList(key) | Retrieves a list of strings for the given key | List<String>? |
| setString(key, value) | Sets a string value for the given key | void |
| setInt(key, value) | Sets an integer value for the given key | void |
| setDouble(key, value) | Sets a double value for the given key | void |
| setBool(key, value) | Sets a boolean value for the given key | void |
| setStringList(key, value) | Sets a list of strings for the given key | void |
Note: SharedPreferences in Flutter is a key-value storage solution that persists data locally on the device. It's ideal for storing simple data types like strings, numbers, and booleans.
Warning: SharedPreferences is not suitable for storing sensitive data like passwords or API keys. For such use cases, consider using secure storage solutions like
flutter_secure_storage.