import 'dart:developer'; | |
import 'package:hive/hive.dart'; | |
/// A simple class to store as static strings your boxes names | |
class HiveClassName { | |
static const String user = "user"; | |
} | |
/// I often add those lines: | |
/// try { | |
/// Hive.openBox<T>(className); | |
/// } catch (e) { | |
/// log(e.toString()); | |
/// } | |
/// | |
/// It is just in case your boxes close | |
/// due to something or a delete you made before | |
class HiveService { | |
Future<void> save<T extends HiveObject>( | |
T data, | |
String className, { | |
int index = 0, | |
}) async { | |
try { | |
await Hive.openBox<T>(className); | |
} catch (e) { | |
log(e.toString()); | |
} | |
Box<T> box = Hive.box(className); | |
if (box.isNotEmpty) { | |
await box.putAt(index, data); | |
} else { | |
await box.add(data); | |
} | |
} | |
T? readData<T extends HiveObject>( | |
String className, { | |
int index = 0, | |
}) { | |
try { | |
Hive.openBox<T>(className); | |
} catch (e) { | |
log(e.toString()); | |
} | |
Box<T> box = Hive.box(className); | |
T? data = box.getAt(index); | |
return data; | |
} | |
List<T>? readDatas<T extends HiveObject>(String className) { | |
try { | |
Hive.openBox<T>(className); | |
} catch (e) { | |
log(e.toString()); | |
} | |
Box<T> box = Hive.box(className); | |
List<T>? data = box.values.toList(); | |
return data; | |
} | |
Future<void> deleteBoxes<T>(String className) async { | |
try { | |
Box<T> box = Hive.box(className); | |
await box.deleteFromDisk(); | |
} catch (e) { | |
log(e.toString()); | |
} | |
} | |
} |