Last active
February 22, 2022 21:08
-
-
Save NemesisX1/b2a1ff84df652b9e330b8007ae5af610 to your computer and use it in GitHub Desktop.
A collection of snippets to speed up your development using Hive as a database in Dart with/without Flutter.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment