Skip to content

Instantly share code, notes, and snippets.

@folaoluwafemi
Last active February 25, 2023 14:08
Show Gist options
  • Save folaoluwafemi/902f14e295deb159d4e64ab268da1050 to your computer and use it in GitHub Desktop.
Save folaoluwafemi/902f14e295deb159d4e64ab268da1050 to your computer and use it in GitHub Desktop.
dart mixin for locally caching state
import 'package:flutter/foundation.dart';
import 'package:hive_flutter/adapters.dart';
mixin CachedState<State, CachedType> {
///Function for serializing data from [State] to a more useable [CachedType]
///that can be stored easily by [Hive]
CachedType toCacheData();
///Function for serializing data from [CachedType] to a more useable [State]
State fromCachedData(CachedType data);
///State Key:
///
///this is the key that will be used to uniquely identify this state from others
///it must be overriden to avoid errors
String? key;
///Cache Key getter:
///
///this is returns the current State's cache Key or a default value
///note that this default value is equal to "Type || Type"
///Do well to override [key]
String get cacheKey {
return key ?? '${State.runtimeType} || ${CachedType.runtimeType}';
}
String get _cacheDataKey => '$cacheKey-cacheData';
bool cacheInitialized = false;
@protected
Future<void> initializeCache() async {
assert(!cacheInitialized, 'Has already been initialized');
cacheInitialized = true;
_cacheBox = await Hive.openBox<CachedType>(cacheKey);
}
Stream<BoxEvent> get cacheChanges {
assert(cacheInitialized, 'Must Be Initialized First');
return _cacheBox.watch();
}
late final Box<CachedType> _cacheBox;
void close() {
_cacheBox.close();
cacheInitialized = false;
}
State? fetchCache() {
assert(cacheInitialized, 'Must Be Initialized First');
CachedType? data = _cacheBox.get(_cacheDataKey);
State? state = data == null ? null : fromCachedData(data);
return state;
}
Future<void> clearCache() async {
assert(cacheInitialized, 'Must Be Initialized First');
await _cacheBox.clear();
}
Future<void> saveCache() async {
assert(cacheInitialized, 'Must Be Initialized First');
CachedType cacheData = toCacheData();
await _cacheBox.put(_cacheDataKey, cacheData);
}
}
@Jethro007
Copy link

Nice !!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment