Hive Documentation

repository·main·Indexed 26 days ago

https://github.com/isar/hive

A 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.

Tokens
3K
Snippets
14
Records
21
Agent score
88%

What's inside Hive

  1. Overview of Hive Boxes

    main
    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.
  2. Store non-primitive Dart objects

    main

    To store custom Dart objects, the object must implement .fromJson() and .toJson() methods. You must also register an adapter for the class using Hive.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);
  3. Configure the Hive default directory

    main

    Before using Hive, you must designate a directory where it can store its data. It is recommended to use path_provider to find the optimal directory for the current platform (e.g., getApplicationDocumentsDirectory()) and assign it to Hive.defaultDirectory.

    void main() async {
      WidgetsFlutterBinding.ensureInitialized();
      final dir = await getApplicationDocumentsDirectory();
      Hive.defaultDirectory = dir.path;
    
      // ...
    }
  4. Install Hive and dependencies

    main

    To use Hive in a Flutter project, create a new project and add the following dependencies to your pubspec.yaml file:

    • 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.0
  5. Initialize Hive with a default directory

    main

    Before using Hive in a Flutter application, you must ensure Flutter is initialized and set the Hive.defaultDirectory to a valid path on the device (typically the application documents directory) using path_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());
    }
  6. Install Hive dependencies

    main

    To use Hive in your Flutter or Dart project, add hive, isar_flutter_libs, and path_provider to your pubspec.yaml file. path_provider is 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.0
  7. Perform basic Hive operations: Open box, Add data, and Read data

    main

    Hive uses 'Boxes' to store data. You can interact with them using the following patterns:

    1. Access a Box: Use Hive.box<T>(name) to access an existing box of a specific type.
    2. Add Data: Use the .add(value) method on a box instance to append data.
    3. Read Data: Use the .values property on a box to retrieve all stored items, which can be converted to a list using .toList().
  8. Perform basic Hive operations: Put and Get

    main

    Once configured, you can interact with Hive using boxes. Use Hive.box() to access a box and put(key, value) to store data. Retrieve data using get(key).

    import 'package:hive/hive.dart';
    
    final box = Hive.box();
    box.put('name', 'David');
    
    final name = box.get('name');
    print('Name: $name');
  9. Use Hive boxes as lists

    main

    Boxes 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';
  10. Enforce type safety in boxes

    main

    You 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 error
  11. Perform atomic transactions

    main

    Use box.write() and box.read() to group multiple operations. Transactions are atomic: if an error occurs during a write transaction, 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');
    });
  12. Insert and update data in a box

    main

    Hive 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';