Hive Documentation
repository·main·Indexed 26 days ago
https://github.com/isar/hiveA lightweight, fast, and secure NoSQL key-value database for Flutter and Dart applications. Hive supports mobile, desktop, and web platforms, organizing data into flexible containers called boxes. It features support for custom object storage via type adapters, AES-256 encryption, atomic transactions, and the ability to run operations in separate isolates using Hive.compute to avoid blocking the UI thread.
What's inside Hive
- In Hive, data is organized into containers called boxes. Boxes are flexible NoSQL containers that do not require a fixed schema and can store a variety of data types. Boxes can also be encrypted to secure sensitive information.
Store non-primitive Dart objects
mainTo store custom Dart objects, the object must implement
.fromJson()and.toJson()methods. You must also register an adapter for the class usingHive.registerAdapter()before using it.class Bee { Bee({required this.name, required this.role}); factory Bee.fromJson(Map<String, dynamic> json) => Bee( name: json['name'] as String, role: json['role'] as String, ); final String name; final String role; Map<String, dynamic> toJson() => { 'name': name, 'role': role, }; } // Register the adapter Hive.registerAdapter('Bee', Bee.fromJson); // Use the box final box = Hive.box(); final bumble = Bee(name: 'Bumble', role: 'Worker'); box.put('BumbleID', bumble);Configure the Hive default directory
mainBefore using Hive, you must designate a directory where it can store its data. It is recommended to use
path_providerto find the optimal directory for the current platform (e.g.,getApplicationDocumentsDirectory()) and assign it toHive.defaultDirectory.void main() async { WidgetsFlutterBinding.ensureInitialized(); final dir = await getApplicationDocumentsDirectory(); Hive.defaultDirectory = dir.path; // ... }Install Hive and dependencies
mainTo use Hive in a Flutter project, create a new project and add the following dependencies to your
pubspec.yamlfile:hive: The core database engine.isar_flutter_libs: Required libraries for Hive/Isar functionality.path_provider: To access the device's local file system for storage.
dependencies: flutter: sdk: flutter hive: ^4.0.0 isar_flutter_libs: ^4.0.0-dev.13 path_provider: ^2.0.0Initialize Hive with a default directory
mainBefore using Hive in a Flutter application, you must ensure Flutter is initialized and set the
Hive.defaultDirectoryto a valid path on the device (typically the application documents directory) usingpath_provider.import 'package:flutter/material.dart'; import 'package:hive/hive.dart'; import 'package:path_provider/path_provider.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); final directory = await getApplicationDocumentsDirectory(); Hive.defaultDirectory = directory.path; runApp(BeeApp()); }Install Hive dependencies
mainTo use Hive in your Flutter or Dart project, add
hive,isar_flutter_libs, andpath_providerto yourpubspec.yamlfile.path_provideris used to locate the appropriate directory for data storage on different platforms.dependencies: hive: ^4.0.0 isar_flutter_libs: ^4.0.0-dev.13 path_provider: ^2.1.0Perform basic Hive operations: Open box, Add data, and Read data
mainHive uses 'Boxes' to store data. You can interact with them using the following patterns:
- Access a Box: Use
Hive.box<T>(name)to access an existing box of a specific type. - Add Data: Use the
.add(value)method on a box instance to append data. - Read Data: Use the
.valuesproperty on a box to retrieve all stored items, which can be converted to a list using.toList().
- Access a Box: Use
Perform basic Hive operations: Put and Get
mainOnce configured, you can interact with Hive using boxes. Use
Hive.box()to access a box andput(key, value)to store data. Retrieve data usingget(key).import 'package:hive/hive.dart'; final box = Hive.box(); box.put('name', 'David'); final name = box.get('name'); print('Name: $name');Use Hive boxes as lists
mainBoxes can be used like lists by using auto-incrementing integer keys.
box.add(value): Appends a value to the box.box.getAt(index): Retrieves a value at a specific index.box[index]: Map-style syntax for index-based access.box[index] = value: Updates a value at a specific index.
Warning: Index-based operations will throw an error if the index is out of bounds.
final box = Hive.box(); box.add('Rose'); box.add('Tulip'); print(box.getAt(0)); // Rose print(box[0]); // Rose box[0] = 'Daffodil';Enforce type safety in boxes
mainYou can specify a generic type when opening a box to ensure only values of that type are stored.
Note: You must use the same type whenever you access the box. Attempting to open the same box with a different type will result in an error.
final box = Hive.box<String>(name: 'BeeTreasures'); box.put('DaisyDance', 'SweetNectarShake'); // box.put('TulipTango', 777); // This would cause an errorPerform atomic transactions
mainUse
box.write()andbox.read()to group multiple operations. Transactions are atomic: if an error occurs during awritetransaction, none of the changes are applied, ensuring data consistency.final box = Hive.box(); box.write(() { box.store('nectar1', 'GoldenNectar'); box.store('nectar2', 'WildflowerBrew'); }); box.read(() { final val = box.get('nectar1'); });Insert and update data in a box
mainHive boxes act as key-value stores (similar to a
Map<String, dynamic>). You can insert or update values using.put(),.putAll(), or the map subscript operator[].box.put(key, value): Inserts or updates a single key-value pair.box.putAll({'key1': val1, 'key2': val2}): Inserts multiple pairs at once.box['key'] = value: Map-style syntax for updating/inserting.
final box = Hive.box(); box.put('danceMoves', 'Waggle Dance'); box.put('wingSpeed', 200); box.putAll({'favoriteFlower': 'Lavender', 'wingSpeed': 210}); // Map syntax box['danceMoves'] = 'Round Dance';