import 'dart:convert'; import 'package:flutter/foundation.dart'; import…
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
import 'dart:convert'; import 'package:flutter/foundation.dart'; import 'package:injectable/injectable.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:tap_that/core/app_logger.dart';
/// An abstract class that provides a standardized interface for interacting
/// with SharedPreferences. It handles basic key-value storage as well
/// as more complex object caching with JSON serialization.
///
/// This abstraction is designed to be used with the injectable package
/// for easy dependency injection.
@lazySingleton
abstract class DataStorageSharedPref {
/// Factory constructor for creating a DataStorageSharedPref instance.
@factoryMethod
const factory DataStorageSharedPref({required SharedPreferences storage}) =
_DataStorageImpl;
/// Writes a value to storage based on its type.
///
/// Supports int, bool, double, String, and List<String>.
/// Returns true on success and false on failure.
Future write({required String key, required dynamic data});
/// Reads a value from storage, casting it to the specified generic type [T].
///
/// Returns the value if found and successfully cast, otherwise returns null.
T? read({required String key});
/// Removes a value from storage by its [key]. Future remove({required String key});
/// Removes all data from storage. Future removeAll();
/// Checks if a [key] exists in storage. Future containsKey({required String key});
/// -- API Response Caching --
/// Serializes and saves a response object to storage.
///
/// The [key] can be a primitive type or an object with a toJson() method.
/// The [value] can also be a primitive or an object with toJson().
/// The [path] is used as a prefix to create a unique storage key.
Future saveResponse<K, V>({
required K key,
required V? value,
String? path,
});
/// Retrieves and deserializes a response object from storage. /// /// The [key] is used to find the stored data. The [fromJson] function is /// required to convert the stored JSON map back into an object of type [V]. Future getResponse<K, V>({ required K key, required V Function(Map<String, dynamic>) fromJson, String? path, }); }
class _DataStorageImpl implements DataStorageSharedPref { const _DataStorageImpl({required this.storage}); final SharedPreferences storage;
@override Future write({required String key, required dynamic data}) async { try { if (data is int) return await storage.setInt(key, data); if (data is bool) return await storage.setBool(key, data); if (data is double) return await storage.setDouble(key, data); if (data is String) return await storage.setString(key, data); if (data is List) return await storage.setStringList(key, data); } on Exception catch (e, stackTrace) { AppLogger.logException(e, stackTrace: stackTrace, message: 'Failed to write to SharedPreferences for key: $key'); } return false; }
@override T? read({required String key}) { try { final value = storage.get(key); if (value is T) { return value; } } on Exception catch (e, stackTrace) { AppLogger.logException(e, stackTrace: stackTrace, message: 'Failed to read from SharedPreferences for key: $key'); } return null; }
@override Future remove({required String key}) async { try { return await storage.remove(key); } on Exception catch (e, stackTrace) { AppLogger.logException(e, stackTrace: stackTrace, message: 'Failed to remove from SharedPreferences for key: $key'); return false; } }
@override Future removeAll() async { try { return await storage.clear(); } on Exception catch (e, stackTrace) { AppLogger.logException(e, stackTrace: stackTrace, message: 'Failed to clear SharedPreferences'); return false; } }
@override Future containsKey({required String key}) async { try { return storage.containsKey(key); } on Exception catch (e, stackTrace) { AppLogger.logException(e, stackTrace: stackTrace, message: 'Failed containsKey check for key: $key'); return false; } }
@override Future saveResponse<K, V>({ required K key, required V? value, String? path, }) async { try { final String storageKey = _encodeCacheKey(key, path); String encodedValue;
// Encode the value to a JSON string.
if (value is String || value is num || value is bool) {
encodedValue = jsonEncode(value.toString());
} else {
// This will throw if the object doesn't have a toJson method.
final jsonValueMap = (value as dynamic).toJson();
encodedValue = jsonEncode(jsonValueMap);
}
if (kDebugMode) {
_logWrite(storageKey, key, value, encodedValue);
}
return write(key: storageKey, data: encodedValue);
} on Exception catch (e, stackTrace) {
AppLogger.logException(
e,
stackTrace: stackTrace,
message: 'Failed to save response. Ensure object has toJson() method.',
);
return false;
}
}
@override Future getResponse<K, V>({ required K key, required V Function(Map<String, dynamic>) fromJson, String? path, }) { final String storageKey = _encodeCacheKey(key, path); final String? encodedValue = read(key: storageKey);
if (encodedValue == null) {
debugPrint('| CACHE MISS: $storageKey');
return Future.error(Exception('Cache miss: No data found for key.'));
}
try {
final decodedJson = jsonDecode(encodedValue) as Map<String, dynamic>;
final result = fromJson(decodedJson);
if (kDebugMode) {
_logRead(storageKey, key, result, encodedValue);
}
return Future.value(result);
} on Exception catch (e, stackTrace) {
AppLogger.logException(
e,
stackTrace: stackTrace,
message: 'Failed to decode cached response for key: $storageKey',
);
// It's often better to not re-throw here unless the caller needs to handle it.
// Depending on the use case, returning an error or a default value might be better.
return Future.error(Exception('Error decoding cached response: $e'));
}
}
/// Encodes a generic key [K] and an optional [path] into a unique string /// suitable for use as a storage key. String _encodeCacheKey(K key, String? path) { String encodedKey; if (key is String || key is num || key is bool) { encodedKey = key.toString(); } else { // ignore: avoid_dynamic_calls final jsonKeyMap = (key as dynamic).toJson(); encodedKey = jsonEncode(jsonKeyMap); } return 'encodedKey'; }
// --- Logging Helpers ---
void _logWrite<K, V>(String finalKey, K key, V value, String encodedValue) { if (!kDebugMode) return; final log = StringBuffer() ..writeln('|------------------ WRITE CACHE -------------------|') ..writeln('| PATH: {key.runtimeType}') ..writeln('| VALUE TYPE: {utf8.encode(encodedValue).length} bytes') ..writeln('|__________________________________________________|'); debugPrint(log.toString()); }
void _logRead<K, V>(String finalKey, K key, V value, String encodedValue) { if (!kDebugMode) return; final log = StringBuffer() ..writeln('|------------------- READ CACHE -------------------|') ..writeln('| PATH: {key.runtimeType}') ..writeln('| VALUE TYPE: {utf8.encode(encodedValue).length} bytes') ..writeln('|__________________________________________________|'); debugPrint(log.toString()); } }
// NOTE: To complete this setup with injectable, you would typically create
// a module to tell the dependency injector how to create third-party
// instances like SharedPreferences.
/*
import 'package:injectable/injectable.dart';
import 'package:shared_preferences/shared_preferences.dart';
@module abstract class RegisterModule { @preResolve // Ensures SharedPreferences is initialized before the app starts Future get prefs => SharedPreferences.getInstance(); } */ optimize this
Here's an optimized version of your DataStorageSharedPref class with improved performance, error handling, and maintainability:
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:injectable/injectable.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:tap_that/core/app_logger.dart';
/// An abstract class that provides a standardized interface for interacting
/// with `SharedPreferences`. It handles basic key-value storage as well
/// as more complex object caching with JSON serialization.
@lazySingleton
abstract class DataStorageSharedPref {
@factoryMethod
const factory DataStorageSharedPref({required SharedPreferences storage}) =
_DataStorageImpl;
/// Writes a value to storage based on its type.
Future<bool> write({required String key, required dynamic data});
/// Reads a value from storage, casting it to the specified generic type [T].
T? read<T>({required String key});
/// Removes a value from storage by its [key].
Future<bool> remove({required String key});
/// Removes all data from storage.
Future<bool> removeAll();
/// Checks if a [key] exists in storage.
bool containsKey({required String key});
/// Serializes and saves a response object to storage.
Future<bool> saveResponse<K, V>({
required K key,
required V? value,
String? path,
});
/// Retrieves and deserializes a response object from storage.
Future<V?> getResponse<K, V>({
required K key,
required V Function(Map<String, dynamic>) fromJson,
String? path,
});
/// Batch operations for better performance
Future<bool> writeBatch(Map<String, dynamic> data);
/// Get multiple keys at once
Map<String, T?> readBatch<T>(List<String> keys);
}
class _DataStorageImpl implements DataStorageSharedPref {
const _DataStorageImpl({required this.storage});
final SharedPreferences storage;
// Cache for frequently accessed keys to reduce SharedPreferences calls
static final Map<String, dynamic> _memoryCache = <String, dynamic>{};
static const int _maxCacheSize = 100;
@override
Future<bool> write({required String key, required dynamic data}) async {
try {
// Update memory cache
_updateMemoryCache(key, data);
// Write to SharedPreferences based on type
return switch (data) {
int value => await storage.setInt(key, value),
bool value => await storage.setBool(key, value),
double value => await storage.setDouble(key, value),
String value => await storage.setString(key, value),
List<String> value => await storage.setStringList(key, value),
_ => false,
};
} catch (e, stackTrace) {
AppLogger.logException(
e,
stackTrace: stackTrace,
message: 'Failed to write to SharedPreferences for key: $key',
);
return false;
}
}
@override
T? read<T>({required String key}) {
try {
// Check memory cache first
if (_memoryCache.containsKey(key)) {
final cachedValue = _memoryCache[key];
if (cachedValue is T) return cachedValue;
}
// Read from SharedPreferences
final value = storage.get(key);
if (value is T) {
_updateMemoryCache(key, value);
return value;
}
} catch (e, stackTrace) {
AppLogger.logException(
e,
stackTrace: stackTrace,
message: 'Failed to read from SharedPreferences for key: $key',
);
}
return null;
}
@override
Future<bool> remove({required String key}) async {
try {
_memoryCache.remove(key);
return await storage.remove(key);
} catch (e, stackTrace) {
AppLogger.logException(
e,
stackTrace: stackTrace,
message: 'Failed to remove from SharedPreferences for key: $key',
);
return false;
}
}
@override
Future<bool> removeAll() async {
try {
_memoryCache.clear();
return await storage.clear();
} catch (e, stackTrace) {
AppLogger.logException(
e,
stackTrace: stackTrace,
message: 'Failed to clear SharedPreferences',
);
return false;
}
}
@override
bool containsKey({required String key}) {
try {
return _memoryCache.containsKey(key) || storage.containsKey(key);
} catch (e, stackTrace) {
AppLogger.logException(
e,
stackTrace: stackTrace,
message: 'Failed containsKey check for key: $key',
);
return false;
}
}
@override
Future<bool> writeBatch(Map<String, dynamic> data) async {
try {
final futures = data.entries.map((entry) =>
write(key: entry.key, data: entry.value)
);
final results = await Future.wait(futures);
return results.every((result) => result);
} catch (e, stackTrace) {
AppLogger.logException(
e,
stackTrace: stackTrace,
message: 'Failed to write batch data',
);
return false;
}
}
@override
Map<String, T?> readBatch<T>(List<String> keys) {
final result = <String, T?>{};
for (final key in keys) {
result[key] = read<T>(key: key);
}
return result;
}
@override
Future<bool> saveResponse<K, V>({
required K key,
required V? value,
String? path,
}) async {
if (value == null) return false;
try {
final storageKey = _encodeCacheKey(key, path);
final encodedValue = _encodeValue(value);
if (kDebugMode) {
_logWrite(storageKey, key, value, encodedValue);
}
return await write(key: storageKey, data: encodedValue);
} catch (e, stackTrace) {
AppLogger.logException(
e,
stackTrace: stackTrace,
message: 'Failed to save response. Ensure object has toJson() method.',
);
return false;
}
}
@override
Future<V?> getResponse<K, V>({
required K key,
required V Function(Map<String, dynamic>) fromJson,
String? path,
}) async {
try {
final storageKey = _encodeCacheKey(key, path);
final encodedValue = read<String>(key: storageKey);
if (encodedValue == null) {
if (kDebugMode) debugPrint('| CACHE MISS: $storageKey');
return null;
}
final decodedJson = jsonDecode(encodedValue);
// Handle both direct values and objects
final result = decodedJson is Map<String, dynamic>
? fromJson(decodedJson)
: fromJson({'value': decodedJson});
if (kDebugMode) {
_logRead(storageKey, key, result, encodedValue);
}
return result;
} catch (e, stackTrace) {
AppLogger.logException(
e,
stackTrace: stackTrace,
message: 'Failed to decode cached response for key: ${_encodeCacheKey(key, path)}',
);
return null;
}
}
/// Encodes a value to JSON string with better type handling
String _encodeValue<V>(V value) {
return switch (value) {
String() || num() || bool() => jsonEncode(value),
_ => jsonEncode((value as dynamic).toJson()),
};
}
/// Encodes a generic key [K] and an optional [path] into a unique string
String _encodeCacheKey<K>(K key, String? path) {
final encodedKey = switch (key) {
String() || num() || bool() => key.toString(),
_ => jsonEncode((key as dynamic).toJson()),
};
return '${path ?? 'cache'}/$encodedKey';
}
/// Updates memory cache with size limit
void _updateMemoryCache(String key, dynamic value) {
if (_memoryCache.length >= _maxCacheSize) {
// Remove oldest entry (simple FIFO strategy)
final firstKey = _memoryCache.keys.first;
_memoryCache.remove(firstKey);
}
_memoryCache[key] = value;
}
// --- Optimized Logging Helpers ---
void _logWrite<K, V>(String finalKey, K key, V value, String encodedValue) {
if (!kDebugMode) return;
debugPrint('''
|------------------ WRITE CACHE -------------------|
| PATH: $finalKey
| KEY TYPE: ${key.runtimeType}
| VALUE TYPE: ${value.runtimeType}
| SIZE: ${utf8.encode(encodedValue).length} bytes
|__________________________________________________|''');
}
void _logRead<K, V>(String finalKey, K key, V value, String encodedValue) {
if (!kDebugMode) return;
debugPrint('''
|------------------- READ CACHE -------------------|
| PATH: $finalKey
| KEY TYPE: ${key.runtimeType}
| VALUE TYPE: ${value.runtimeType}
| SIZE: ${utf8.encode(encodedValue).length} bytes
|__________________________________________________|''');
}
}
// Enhanced module with better error handling
@module
abstract class RegisterModule {
@preResolve
Future<SharedPreferences> get prefs async {
try {
return await SharedPreferences.getInstance();
} catch (e) {
AppLogger.logException(
e,
message: 'Failed to initialize SharedPreferences',
);
rethrow;
}
}
}
writeBatch() and readBatch() methodsgetResponse() now returns V? instead of throwingcontainsKey()This optimized version provides better performance, especially for frequently accessed data, while maintaining the same API surface and adding useful batch operations.