All box registers are registered as CacheModel type. So, multiple types are not allowed in this architecture. Following line is the point of this problem.
|
Hive.registerAdapter('${item.runtimeType}', item.fromDynamicJson); |
My solution (is 3 steps):
- Create a new function called
registerCacheModel in CacheManager interface.
/// Cache manager interface
abstract interface class CacheManager {
/// Get ready to use the cache manager
Future<void> init(); // => REMOVE ITEMS PARAMETER HERE
/// Register a cache model type to the cache manager.
void registerCacheModel<T extends CacheModel>(
T model); // => CREATE A NEW FUNCTION
/// Remove the stored cache
void remove();
/// Get the path to the cache
String? get path;
}
- In
HiveCacheManager (implementation of CacheManager) move the box registering section to registerCacheModel from init function.
@override
Future<void> init() async {
final dir = _path ?? (await getApplicationDocumentsDirectory()).path;
Directory(dir).createSync(recursive: true);
Hive.defaultDirectory = dir;
// move registering box section from here
}
@override
void registerCacheModel<T extends CacheModel>(T modelSample) {
Hive.registerAdapter<T>( // => Pass the generic type T to register all unique cache model classes
modelSample.runtimeType.toString(),
(json) => modelSample.fromJson(json) as T, // => Type casting is required.
);
}
- Register all of your cache models in
ProductCache.init function.
Future<void> init() async {
// Old method. remove this part
// await _cacheManager.init(items: [
// GameSaveCacheModel.empty(),
// DeviceIdCacheModel.empty(),
// ]);
// initializes hives folder
await _cacheManager.init();
// register cache models instead of passing model list.
_cacheManager
..registerCacheModel<GameSaveCacheModel>(GameSaveCacheModel.empty())
..registerCacheModel<DeviceIdCacheModel>(DeviceIdCacheModel.empty());
}
All box registers are registered as
CacheModeltype. So, multiple types are not allowed in this architecture. Following line is the point of this problem.architecture_template_v2/module/core/lib/src/cache/hive/hive_cache_manager.dart
Line 19 in cc03005
My solution (is 3 steps):
registerCacheModelinCacheManagerinterface.HiveCacheManager(implementation ofCacheManager) move the box registering section toregisterCacheModelfrominitfunction.ProductCache.initfunction.