Line data Source code
1 : import 'dart:async'; 2 : 3 : import 'package:hive/hive.dart'; 4 : import 'package:riverpod/riverpod.dart'; 5 : import 'package:path/path.dart' as path_helper; 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 : If using Riverpod, did you supply the override? 34 : 35 : Widget build(context) { 36 : return ProviderContainer( 37 : overrides: [ 38 : configureRepositoryLocalStorage() 39 : ], 40 : child: MaterialApp( 41 : 42 : If using Provider, did you include the providers? 43 : 44 : Widget build(context) { 45 : return MultiProvider( 46 : providers: [ 47 : ...repositoryProviders(), 48 : ], 49 : child: MaterialApp( 50 : '''); 51 : } 52 : 53 4 : final path = path_helper.join(await baseDirFn!(), 'flutter_data'); 54 2 : hive.init(path); 55 : 56 1 : isInitialized = true; 57 : } 58 : 59 0 : Future<Box<B>> openBox<B>(String name) async { 60 0 : return await hive.openBox<B>(name, encryptionCipher: encryptionCipher); 61 : } 62 : 63 0 : Future<void> deleteBox(String name) async { 64 : // if hard clear, remove box 65 : try { 66 0 : if (await hive.boxExists(name)) { 67 0 : await hive.deleteBoxFromDisk(name); 68 : } 69 : } catch (e) { 70 : // weird fs bug? where even after checking for file.exists() 71 : // in Hive, it throws a No such file or directory error 72 0 : if (e.toString().contains('No such file or directory')) { 73 : // we can safely ignore? 74 : } else { 75 : rethrow; 76 : } 77 : } 78 : } 79 : } 80 : 81 2 : final hiveLocalStorageProvider = 82 1 : Provider<HiveLocalStorage>((ref) => HiveLocalStorage(baseDirFn: () => ''));