Storage
The StorageFeature
provides a powerful, type-safe, and organized approach to data persistence in Flutter applications. It wraps SharedPreferences with additional functionality for structured data storage, user-specific data, and JSON object serialization.
Getting Started
Section titled “Getting Started”Add the Feature to your FlexCore Initialization
Section titled “Add the Feature to your FlexCore Initialization”await FlexCore.initialize([ // Other features... StorageFeature(), // More features...]);
Access Storage Through FlexCore
Section titled “Access Storage Through FlexCore”// FlexCore provides a convenient accessor for storagefinal storage = FlexCore.storage;
Basic Usage
Section titled “Basic Usage”Store and Retrieve Values
Section titled “Store and Retrieve Values”// Store valuesawait FlexCore.storage.setString('app_name', 'My Awesome App', group: StorageGroup.app);await FlexCore.storage.setBool('dark_mode', true, group: StorageGroup.ui);await FlexCore.storage.setInt('launch_count', 5);
// Retrieve valuesfinal appName = FlexCore.storage.getString('app_name', group: StorageGroup.app);final isDarkMode = FlexCore.storage.getBool('dark_mode', group: StorageGroup.ui, defaultValue: false);final launchCount = FlexCore.storage.getInt('launch_count', defaultValue: 0);
Supported Value Types
Section titled “Supported Value Types”- Strings:
getString
/setString
- Booleans:
getBool
/setBool
- Integers:
getInt
/setInt
- Doubles:
getDouble
/setDouble
- String Lists:
getStringList
/setStringList
- Custom Objects:
getObject
/setObject
- Lists of Custom Objects:
getObjectList
/setObjectList
Organizing Data with Storage Groups
Section titled “Organizing Data with Storage Groups”enum StorageGroup { user('user'), // User-specific settings app('app'), // App-level settings cache('cache'), // Temporary cache data custom('custom'), // Custom or miscellaneous data}
Use storage groups to organize your data and enable selective clearing:
// Store in different groupsawait FlexCore.storage.setString('theme', 'dark', group: StorageGroup.ui);await FlexCore.storage.setString('auth_token', 'xyz123', group: StorageGroup.user);await FlexCore.storage.setStringList('recent_searches', ['flutter', 'dart'], group: StorageGroup.cache);
// Clear specific groupawait FlexCore.storage.clearGroup(StorageGroup.cache); // Only clears cache data
User-Specific Storage
Section titled “User-Specific Storage”Designate data to be associated with specific users:
// Set the active userawait FlexCore.storage.setActiveUser('user_123');
// Store user-specific dataawait FlexCore.storage.setString('name', 'John Doe', group: StorageGroup.user, userSpecific: true);
// Later, after user logout, clear user dataawait FlexCore.storage.clearUserData();await FlexCore.storage.clearActiveUser();
// Switch to a different userawait FlexCore.storage.setActiveUser('user_456');
// Access the new user's datafinal userName = FlexCore.storage.getString('name', group: StorageGroup.user, userSpecific: true, defaultValue: 'Guest');
Working with Custom Objects
Section titled “Working with Custom Objects”For domain models and complex objects, use the object storage methods:
1. Prepare Your Model Class
Section titled “1. Prepare Your Model Class”class UserPreferences { final bool darkMode; final String accentColor; final List<String> recentSearches;
UserPreferences({ required this.darkMode, required this.accentColor, required this.recentSearches, });
factory UserPreferences.fromJson(Map<String, dynamic> json) { return UserPreferences( darkMode: json['darkMode'] as bool, accentColor: json['accentColor'] as String, recentSearches: List<String>.from(json['recentSearches']), ); }
Map<String, dynamic> toJson() { return { 'darkMode': darkMode, 'accentColor': accentColor, 'recentSearches': recentSearches, }; }}
2. Store and Retrieve Objects
Section titled “2. Store and Retrieve Objects”// Create an objectfinal prefs = UserPreferences( darkMode: true, accentColor: 'blue', recentSearches: ['flutter', 'dart'],);
// Store objectawait FlexCore.storage.setObject<UserPreferences>( 'user_preferences', prefs, toJson: (obj) => obj.toJson(), group: StorageGroup.user, userSpecific: true,);
// Retrieve objectfinal userPrefs = FlexCore.storage.getObject<UserPreferences>( 'user_preferences', fromJson: (json) => UserPreferences.fromJson(json), group: StorageGroup.user, userSpecific: true,);
3. Working with Lists of Objects
Section titled “3. Working with Lists of Objects”// Store a list of objectsfinal recentSearches = [ RecentSearch(query: 'flutter', timestamp: DateTime.now()), RecentSearch(query: 'dart', timestamp: DateTime.now()),];
await FlexCore.storage.setObjectList<RecentSearch>( 'search_history', recentSearches, toJson: (obj) => obj.toJson(), group: StorageGroup.user, userSpecific: true,);
// Retrieve a list of objectsfinal searchHistory = FlexCore.storage.getObjectList<RecentSearch>( 'search_history', fromJson: (json) => RecentSearch.fromJson(json), group: StorageGroup.user, userSpecific: true, defaultValue: [], // Provide a default empty list);
Managing Storage
Section titled “Managing Storage”Check if a Key Exists
Section titled “Check if a Key Exists”final exists = await FlexCore.storage.containsKey('key_name', group: StorageGroup.app);
Remove a Specific Value
Section titled “Remove a Specific Value”await FlexCore.storage.remove('key_name', group: StorageGroup.cache);
Get All Keys
Section titled “Get All Keys”// Get all keysfinal allKeys = FlexCore.storage.getAllKeys();
// Get keys for a specific groupfinal appKeys = FlexCore.storage.getGroupKeys(StorageGroup.app);
// Get keys for the active userfinal userKeys = FlexCore.storage.getUserKeys();
Get Storage Size
Section titled “Get Storage Size”final storageSize = await FlexCore.storage.getStorageSize();print('Current storage size: $storageSize bytes');
Best Practices
Section titled “Best Practices”- Use Storage Groups Consistently: Organize your data logically using storage groups
- Provide Default Values: Always provide default values for
get
operations to handle missing data gracefully - Clear User Data on Logout: Use
clearUserData()
when a user logs out - Handle Errors: Wrap storage operations in try-catch blocks for production code
- Keep Domain Models Serializable: Ensure your model classes have proper
toJson
andfromJson
methods