A simple and efficient singleton class for managing session data in Flutter applications using the shared_preferences
package. This SessionManager
allows you to easily store, retrieve, and manage session data of various types.
- Singleton pattern ensures a single instance throughout the app.
- Supports multiple data types:
String
,int
,bool
,double
,List<String>
, and JSON objects. - Easy-to-use methods for setting, getting, removing, and clearing session data.
Add the following dependency to your pubspec.yaml
file:
dependencies:
shared_preferences: ^2.0.0 # Check for the latest version
- Import the SessionManager
import 'path/to/your/session_manager.dart';
- Initialize
final sessionManager = SessionManager();
- Save data
await sessionManager.set('username', 'john_doe');
await sessionManager.set('age', 30);
await sessionManager.set('isLoggedIn', true);
- Retrieve data
String? username = await sessionManager.get('username');
int? age = await sessionManager.get('age');
bool? isLoggedIn = await sessionManager.get('isLoggedIn');
- Check if key exists
bool exists = await sessionManager.containsKey('username');
- Remove a key
await sessionManager.remove('username');
- Clear all session data
await sessionManager.clear();
Here’s a quick example of how you might use SessionManager in a login flow:
void login(String username, String password) async {
// Perform authentication...
if (isAuthenticated) {
await sessionManager.set('username', username);
}
}
set(String key, dynamic value)
Saves the specified value under the given key.
get(String key)
Retrieves the value associated with the specified key.
getObject(String key)
Retrieves and decodes an object stored as a JSON string.
containsKey(String key)
Checks if the specified key exists in the session.
remove(String key)
Removes the specified key and its associated value.
clear()
Clears all session data.
reload()
Reloads the preferences (automatically handled but can be called if needed).
This project is licensed under MIT License
Contributions are always welcome!
Feel free to open a pull request or issue.
- Shared Preferences for providing a simple way to persist data.