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
Okay, let's optimize the provided DataStorageSharedPref implementation. The goal is to improve robustness, clarity, error handling, and potentially efficiency where possible, while maintaining the existing functionality and structure.
Here are the key areas for optimization:
jsonEncode more directly for primitives and handle potential Format or TypeError during decoding more gracefully. Ensure the toJson call in saveResponse is robust.jsonDecode.null values when saving/retrieving responses.SharedPreferences has specific methods (setInt, setString, etc.). The write method correctly dispatches to these. The optimization will focus on the caching part.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'; // Assuming AppLogger exists and works as shown
/// 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.
/// Requires an initialized `SharedPreferences` 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 (e.g., logging the error).
Future<bool> write({required String key, required dynamic data});
/// Reads a value from storage, attempting to cast it to the specified generic type [T].
///
/// Returns the value if found and successfully cast, otherwise returns `null`.
/// Logs errors if retrieval or casting fails.
T? read<T>({required String key});
/// Removes a value from storage by its [key].
/// Returns `true` on success, `false` on failure.
Future<bool> remove({required String key});
/// Removes all data from storage.
/// Returns `true` on success, `false` on failure.
Future<bool> removeAll();
/// Checks if a [key] exists in storage.
/// Returns `true` if the key exists, `false` otherwise or on error.
Future<bool> containsKey({required String key});
/// -- API Response Caching --
/// Serializes and saves a response object to storage using JSON encoding.
///
/// Handles primitive types (`String`, `num`, `bool`) and objects with a `toJson()` method.
/// If the `value` is null, it stores the JSON representation of null.
/// The [key] and optional [path] are combined to form the storage key.
/// Returns `true` on success, `false` on failure (logging the error).
Future<bool> saveResponse<K, V>({
required K key,
required V? value,
String? path,
});
/// Retrieves and deserializes a response object from storage.
///
/// The [key] and optional [path] are used to find the stored data.
/// The [fromJson] function is required to convert the stored JSON map back into an object of type [V].
/// Throws an exception (returning `Future.error`) if the data is not found (cache miss),
/// is corrupted, or cannot be decoded.
Future<V> getResponse<K, V>({
required K key,
required V Function(Map<String, dynamic>) fromJson,
String? path,
});
}
class _DataStorageImpl implements DataStorageSharedPref {
/// Constructor requires an instance of SharedPreferences.
const _DataStorageImpl({required this.storage});
final SharedPreferences storage;
/// Writes primitive data types to SharedPreferences.
@override
Future<bool> write({required String key, required dynamic data}) async {
try {
// Use SharedPreferences methods directly for primitive types
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<String>) return await storage.setStringList(key, data);
// Log if the type is unsupported by SharedPreferences directly
AppLogger.logWarning(
message: 'Unsupported data type for direct SharedPreferences write: ${data.runtimeType}',
context: {'key': key},
);
return false;
} on SharedPreferencesError catch (e) {
// Catch SharedPreferences specific errors
_logError('write', key, 'SharedPreferencesError', e);
return false;
} on Exception catch (e, stackTrace) {
// Catch any other exceptions during the write operation
_logError('write', key, e.runtimeType.toString(), e, stackTrace);
return false;
}
}
/// Reads a value from SharedPreferences and casts it to type [T].
@override
T? read<T>({required String key}) {
try {
final value = storage.get(key);
// Return null if value is null or not assignable to type T
if (value == null || value is! T) {
if (value != null && kDebugMode) {
// Log mismatch if value exists but is the wrong type
AppLogger.logInfo(
message: 'Value found for key "$key", but type mismatch.',
context: {
'key': key,
'expectedType': T.toString(),
'actualType': value.runtimeType.toString(),
},
);
}
return null;
}
return value as T;
} on SharedPreferencesError catch (e) {
_logError('read', key, 'SharedPreferencesError', e);
return null;
} on Exception catch (e, stackTrace) {
_logError('read', key, e.runtimeType.toString(), e, stackTrace);
return null;
}
}
/// Removes a single key-value pair from storage.
@override
Future<bool> remove({required String key}) async {
try {
return await storage.remove(key);
} on SharedPreferencesError catch (e) {
_logError('remove', key, 'SharedPreferencesError', e);
return false;
} on Exception catch (e, stackTrace) {
_logError('remove', key, e.runtimeType.toString(), e, stackTrace);
return false;
}
}
/// Clears all data from storage.
@override
Future<bool> removeAll() async {
try {
return await storage.clear();
} on SharedPreferencesError catch (e) {
_logError('removeAll', '', 'SharedPreferencesError', e);
return false;
} on Exception catch (e, stackTrace) {
_logError('removeAll', '', e.runtimeType.toString(), e, stackTrace);
return false;
}
}
/// Checks if a key exists in storage.
@override
Future<bool> containsKey({required String key}) async {
try {
return storage.containsKey(key);
} on SharedPreferencesError catch (e) {
_logError('containsKey', key, 'SharedPreferencesError', e);
return false;
} on Exception catch (e, stackTrace) {
_logError('containsKey', key, e.runtimeType.toString(), e, stackTrace);
return false;
}
}
/// Encodes and saves a response object (primitive or complex) to storage.
@override
Future<bool> saveResponse<K, V>({
required K key,
required V? value,
String? path,
}) async {
final String storageKey = _encodeCacheKey(key, path);
String encodedValue;
try {
if (value == null) {
// Store JSON null explicitly if the value is null
encodedValue = jsonEncode(null);
} else if (value is String || value is num || value is bool) {
// Use jsonEncode directly for primitives for correct JSON representation
encodedValue = jsonEncode(value);
} else {
// Attempt to get JSON map from object using toJson()
// Use dynamic cast and check for NoSuchMethodError for missing toJson
final dynamic dynamicValue = value;
if (!JsonSerializable.isEncodable(dynamicValue)) {
throw ArgumentError('Value does not implement toJson() or is not encodable by dart:convert.');
}
final Map<String, dynamic> jsonMap = dynamicValue.toJson();
encodedValue = jsonEncode(jsonMap);
}
// Log the write operation details in debug mode
if (kDebugMode) {
_logCacheOperation(
'WRITE',
storageKey,
key,
value.runtimeType.toString(),
encodedValue.length,
);
}
// Use the standard write method to save the encoded string
return await write(key: storageKey, data: encodedValue);
} on ArgumentError catch (e) {
// Catch errors related to missing toJson or unsupported types
_logError('saveResponse', storageKey, 'ArgumentError', e, null, {'originalKey': key.toString()});
return false;
} on JsonUnsupportedObjectError catch (e) {
// Catch errors if toJson returns an unsupported type or fails internally
_logError('saveResponse', storageKey, 'JsonUnsupportedObjectError', e, null, {'originalKey': key.toString()});
return false;
} on SharedPreferencesError catch (e) {
_logError('saveResponse', storageKey, 'SharedPreferencesError', e, null, {'originalKey': key.toString()});
return false;
} on Exception catch (e, stackTrace) {
// Catch any other unexpected errors during encoding or saving
_logError('saveResponse', storageKey, e.runtimeType.toString(), e, stackTrace, {'originalKey': key.toString()});
return false;
}
}
/// Retrieves and deserializes a response object from storage.
@override
Future<V> getResponse<K, V>({
required K key,
required V Function(Map<String, dynamic>) fromJson,
String? path,
}) async {
final String storageKey = _encodeCacheKey(key, path);
final String? encodedValue = read<String>(key: storageKey); // Use the read method
if (encodedValue == null) {
// Cache miss is expected, log info and throw specific error
if (kDebugMode) {
AppLogger.logInfo(
message: 'CACHE MISS',
context: {'key': storageKey, 'originalKey': key.toString()},
);
}
throw Exception('Cache miss: No data found for key "$storageKey".');
}
try {
// Decode the JSON string
final decodedData = jsonDecode(encodedValue);
// Handle potential null stored value
if (decodedData == null) {
// If the stored value was JSON null, and V expects a Map, it's an issue.
// If V could potentially be null or derived from null, adjust logic here.
// Forcing a Map<String, dynamic> means null isn't directly compatible.
AppLogger.logWarning(
message: 'Stored JSON value is null for key "$storageKey".',
context: {'key': storageKey, 'originalKey': key.toString()},
);
// Throw error as we expect a Map<String, dynamic> for fromJson
throw FormatException('Stored JSON value is null, cannot deserialize to Map.');
}
// Ensure the decoded data is a Map<String, dynamic> before passing to fromJson
if (decodedData is! Map<String, dynamic>) {
AppLogger.logError(
message: 'Cached data format error: Expected Map<String, dynamic>, got ${decodedData.runtimeType}.',
context: {'key': storageKey, 'originalKey': key.toString()},
error: FormatException('Invalid cache format'),
stackTrace: StackTrace.current,
);
throw FormatException('Invalid cache format: Expected Map<String, dynamic>.');
}
// Use the provided fromJson factory to create the object
final V result = fromJson(decodedData);
// Log the successful read operation details in debug mode
if (kDebugMode) {
_logCacheOperation(
'READ',
storageKey,
key,
result.runtimeType.toString(),
encodedValue.length,
);
}
return result;
} on FormatException catch (e) {
// Catch errors during JSON decoding (invalid JSON)
_logError('getResponse', storageKey, 'FormatException', e, null, {'originalKey': key.toString()});
throw FormatException('Failed to decode cached JSON for key "$storageKey": ${e.message}');
} on TypeError catch (e) {
// Catch errors if data isn't a Map or during fromJson processing (if it expects wrong types)
_logError('getResponse', storageKey, 'TypeError', e, null, {'originalKey': key.toString()});
throw TypeError('Type error processing cached data for key "$storageKey": ${e.toString()}');
} on Exception catch (e, stackTrace) {
// Catch any other exceptions (e.g., during fromJson execution)
_logError('getResponse', storageKey, e.runtimeType.toString(), e, stackTrace, {'originalKey': key.toString()});
// Rethrow as a generic exception indicating failure
throw Exception('Failed to process cached response for key "$storageKey": ${e.toString()}');
}
}
/// Encodes a generic key [K] and an optional [path] into a unique, URL-safe string
/// suitable for use as a storage key. Handles primitives and objects with `toJson`.
String _encodeCacheKey<K>(K key, String? path) {
String encodedKeyPart;
try {
if (key == null) {
encodedKeyPart = 'null';
} else if (key is String || key is num || key is bool) {
encodedKeyPart = Uri.encodeComponent(key.toString());
} else {
// Use dynamic cast and check for encodability
final dynamic dynamicKey = key;
if (!JsonSerializable.isEncodable(dynamicKey)) {
throw ArgumentError('Key type ${key.runtimeType} is not encodable.');
}
final Map<String, dynamic> jsonKeyMap = dynamicKey.toJson();
encodedKeyPart = Uri.encodeComponent(jsonEncode(jsonKeyMap));
}
} on Exception catch (e) {
// Fallback for key encoding errors, potentially log and use a default key
AppLogger.logError(
message: 'Error encoding cache key',
context: {'key': key.toString(), 'path': path},
error: e,
stackTrace: StackTrace.current
);
// Use a default representation or throw error if key is critical
encodedKeyPart = 'encoding_error_${DateTime.now().millisecondsSinceEpoch}';
}
final String basePath = path ?? 'cache'; // Default path if none provided
// Ensure path doesn't start/end with slash if key is empty/encoded weirdly
return '$basePath/$encodedKeyPart';
}
// --- Logging Helpers ---
/// Logs errors with context.
void _logError(
String operation,
String key,
String errorType,
Object error, [
StackTrace? stackTrace,
Map<String, dynamic>? contextInfo, // Additional context like originalKey
]) {
final Map<String, dynamic> context = {
'operation': operation,
'key': key,
...(contextInfo ?? {}),
};
AppLogger.logError(
message: 'Failed to $operation for key "$key". Error type: $errorType.',
context: context,
error: error,
stackTrace: stackTrace,
);
}
/// Logs cache operations (write/read) in debug mode.
void _logCacheOperation(
String type, // 'WRITE' or 'READ'
String finalKey,
dynamic originalKey,
String valueRuntimeType,
int sizeInBytes,
) {
if (!kDebugMode) return;
final log = StringBuffer()
..writeln('|------------------ CACHE $type -------------------|')
..writeln('| FINAL KEY: $finalKey')
..writeln('| ORIGINAL KEY TYPE: ${originalKey.runtimeType}')
..writeln('| VALUE TYPE: $valueRuntimeType')
..writeln('| SIZE: $sizeInBytes bytes')
..writeln('|__________________________________________________|');
debugPrint(log.toString());
}
}
// Note: Ensure AppLogger has methods like logError, logWarning, logInfo, logDebug.
// Example stub (replace with your actual implementation):
/*
class AppLogger {
static void logError(String message, {dynamic error, StackTrace? stackTrace, Map<String, dynamic>? context}) {
print('[ERROR] $message Context: $context Error: $error');
if (stackTrace != null) print(stackTrace);
}
static void logWarning(String message, {Map<String, dynamic>? context}) {
print('[WARN] $message Context: $context');
}
static void logInfo(String message, {Map<String, dynamic>? context}) {
if (kDebugMode) print('[INFO] $message Context: $context');
}
static void logDebug(String message, {Map<String, dynamic>? context}) {
if (kDebugMode) print('[DEBUG] $message Context: $context');
}
}
*/
// Ensure your injectable setup includes SharedPreferences initialization.
// Example:
/*
@module
abstract class RegisterModule {
@singleton // or @lazySingleton
@preResolve // Ensures SharedPreferences is initialized before use
Future<SharedPreferences> get prefs => SharedPreferences.getInstance();
// The DataStorageSharedPref is already @lazySingleton,
// injectable will find the SharedPreferences instance provided by this module.
}
*/
jsonEncode(value.toString()) to jsonEncode(value) for primitives (String, num, bool). This correctly stores them as JSON numbers (5), booleans (true), or strings ("hello") rather than potentially JSON strings containing those values ("5").saveResponse: Added explicit handling for null values, storing jsonEncode(null).toJson Handling (saveResponse):
JsonSerializable.isEncodable() check before calling toJson to provide a clearer error message if the object isn't meant to be encoded.ArgumentError (often thrown if toJson is missing or invalid) and JsonUnsupportedObjectError..toJson() call and subsequent jsonEncode within the try block to catch errors specific to that operation.getResponse):
if (decodedData is! Map<String, dynamic>) after jsonDecode to ensure the data retrieved is in the expected map format before passing it to fromJson.null separately.FormatException and TypeError specifically for decoding/casting issues._logError helper function for consistent error logging format, including operation type, key, error type, the error object, stack trace (optional), and additional context.AppLogger.logError, logWarning, logInfo for different severity levels.getResponse, explicitly logs a "CACHE MISS" message (if in debug mode) before throwing the exception.Uri.encodeComponent to the encoded key parts to ensure they are URL-safe, preventing potential issues if keys contain characters like /, ?, #, etc. Added handling for null keys. Added error handling for key encoding itself._logCacheOperation for better readability and consistency in debug logs.value is! T, decodedData is! Map<String, dynamic>) before casting or using values.///) to clarify the behavior and potential failure points of each method.@preResolve Note: Added a reminder about using @preResolve for SharedPreferences.getInstance() in the injectable module setup.