23 lines
970 B
Dart
Executable File
23 lines
970 B
Dart
Executable File
import 'package:shared_preferences/shared_preferences.dart';
|
|
import 'dart:convert';
|
|
|
|
class SharedPreferenceHelper {
|
|
// Store an object in SharedPreferences
|
|
static Future<void> setPreferenceObject(String key, Object value) async {
|
|
final prefs = await SharedPreferences.getInstance();
|
|
String jsonString = jsonEncode(value); // Convert object to JSON string
|
|
prefs.setString(key, jsonString); // Save JSON string in SharedPreferences
|
|
}
|
|
|
|
// Retrieve an object from SharedPreferences
|
|
static Future<T?> getPreferenceObject<T>(
|
|
String key, T Function(Map<String, dynamic>) fromJson) async {
|
|
final prefs = await SharedPreferences.getInstance();
|
|
String? jsonString = prefs.getString(key); // Get JSON string
|
|
if (jsonString == null) return null;
|
|
Map<String, dynamic> jsonMap =
|
|
jsonDecode(jsonString); // Convert JSON string to Map
|
|
return fromJson(jsonMap); // Convert Map to Object using fromJson
|
|
}
|
|
}
|