From 1c8bd626fa9f7b8deac5bef1d621e66b812e1625 Mon Sep 17 00:00:00 2001 From: TheOneWithTheBraid Date: Tue, 24 May 2022 10:05:00 +0200 Subject: [PATCH] feat: add documentation on BoxCollections - add documentation and example on BoxCollections and Transactions into Readme Signed-off-by: TheOneWithTheBraid --- hive/README.md | 64 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) diff --git a/hive/README.md b/hive/README.md index 473ce63f5..53795e165 100644 --- a/hive/README.md +++ b/hive/README.md @@ -38,6 +38,70 @@ var name = box.get('name'); print('Name: $name'); ``` +## BoxCollections + +`BoxCollections` are a set of boxes which can be similarly used as normal boxes, except of that +they dramatically improve speed on web. They support opening and closing all boxes of a collection +at once and more efficiently store data in indexed DB on web. + +Aside, they also expose Transactions which can be used to speed up tremendous numbers of database +transactions on web. + +On `dart:io` platforms, there is no performance gain by BoxCollections or Transactions. Only +BoxCollections might be useful for some box hierarchy and development experience. + +```dart +// Create a box collection + final collection = await BoxCollection.open( + 'MyFirstFluffyBox', // Name of your database + {'cats', 'dogs'}, // Names of your boxes + path: './', // Path where to store your boxes (Only used in Flutter / Dart IO) + key: HiveCipher(), // Key to encrypt your boxes (Only used in Flutter / Dart IO) + ); + + // Open your boxes. Optional: Give it a type. + final catsBox = collection.openBox('cats'); + + // Put something in + await catsBox.put('fluffy', {'name': 'Fluffy', 'age': 4}); + await catsBox.put('loki', {'name': 'Loki', 'age': 2}); + + // Get values of type (immutable) Map? + final loki = await catsBox.get('loki'); + print('Loki is ${loki?['age']} years old.'); + + // Returns a List of values + final cats = await catsBox.getAll(['loki', 'fluffy']); + print(cats); + + // Returns a List of all keys + final allCatKeys = await catsBox.getAllKeys(); + print(allCatKeys); + + // Returns a Map with all keys and entries + final catMap = await catsBox.getAllValues(); + print(catMap); + + // delete one or more entries + await catsBox.delete('loki'); + await catsBox.deleteAll(['loki', 'fluffy']); + + // ...or clear the whole box at once + await catsBox.clear(); + + // Speed up write actions with transactions + await collection.transaction( + () async { + await catsBox.put('fluffy', {'name': 'Fluffy', 'age': 4}); + await catsBox.put('loki', {'name': 'Loki', 'age': 2}); + // ... + }, + boxNames: ['cats'], // By default all boxes become blocked. + readOnly: false, + ); +``` + + ## Store objects Hive not only supports primitives, lists and maps but also any Dart object you like. You need to generate a type adapter before you can store objects.