Line data Source code
1 : import 'dart:async'; 2 : 3 : import 'package:hive/hive.dart'; 4 : import 'package:path/path.dart' as path_helper; 5 : import 'package:riverpod/riverpod.dart'; 6 : 7 : class HiveLocalStorage { 8 1 : HiveLocalStorage({this.baseDirFn, List<int>? encryptionKey, bool? clear}) 9 : : encryptionCipher = 10 1 : encryptionKey != null ? HiveAesCipher(encryptionKey) : null, 11 : clear = clear ?? false; 12 : 13 2 : HiveInterface get hive => Hive; 14 : final HiveAesCipher? encryptionCipher; 15 : final FutureOr<String> Function()? baseDirFn; 16 : final bool clear; 17 : 18 : bool isInitialized = false; 19 : 20 1 : Future<void> initialize() async { 21 1 : if (isInitialized) return; 22 : 23 1 : if (baseDirFn == null) { 24 1 : throw UnsupportedError(''' 25 : A base directory path MUST be supplied to 26 : the hiveLocalStorageProvider via the `baseDirFn` 27 : callback. 28 : 29 : In Flutter, `baseDirFn` will be supplied automatically if 30 : the `path_provider` package is in `pubspec.yaml` AND 31 : Flutter Data is properly configured: 32 : 33 : Did you supply the override? 34 : 35 : Widget build(context) { 36 : return ProviderContainer( 37 : overrides: [ 38 : configureRepositoryLocalStorage() 39 : ], 40 : child: MaterialApp( 41 : '''); 42 : } 43 : 44 3 : final path = path_helper.join(await baseDirFn!(), 'flutter_data'); 45 2 : hive.init(path); 46 : 47 1 : isInitialized = true; 48 : } 49 : 50 0 : Future<Box<B>> openBox<B>(String name) async { 51 0 : return await hive.openBox<B>(name, encryptionCipher: encryptionCipher); 52 : } 53 : 54 0 : Future<void> deleteBox(String name) async { 55 : // if hard clear, remove box 56 : try { 57 0 : if (await hive.boxExists(name)) { 58 0 : await hive.deleteBoxFromDisk(name); 59 : } 60 : } catch (e) { 61 : // weird fs bug? where even after checking for file.exists() 62 : // in Hive, it throws a No such file or directory error 63 0 : if (e.toString().contains('No such file or directory')) { 64 : // we can safely ignore? 65 : } else { 66 : rethrow; 67 : } 68 : } 69 : } 70 : } 71 : 72 2 : final hiveLocalStorageProvider = 73 1 : Provider<HiveLocalStorage>((ref) => HiveLocalStorage(baseDirFn: () => ''));