Skip to content

Hive

Hive

簡介

  • Hive 是一個輕量、極速的 NoSQL 資料庫,具有以下特點:
    1. 使用純 Dart 撰寫,受到 Bitcask 的啟發。
    2. 支援跨平台應用,包括手機、桌面和瀏覽器。
    3. 具有出色的效能,特別在讀取方面表現優異。
    4. 提供簡單強大的 API,易於使用。
    5. 內建強大的加密功能,保障資料安全。
    6. 無需原生依賴,跨平台適用。
    7. 提供盒子集合和事務功能,可在網路應用中提高效能。
    8. 特別適用於 Flutter 開發,可以直接在 Flutter 小部件的 build() 方法中使用。
    9. 在寫入和刪除方面優於 SQLite 和 SharedPreferences。
    10. 建議在使用基準測試時保持謹慎,因為客觀比較不同資料庫的效能非常困難。

使用方法

建立Box

1
2
3
4
5
6
7
var box = Hive.box('myBox');

box.put('name', 'David');

var name = box.get('name');

print('Name: $name');

從Box中取放值

import 'package:hive/hive.dart';

class HiveService {
  Future<Box> openBox(String boxName) async {
    return await Hive.openBox(boxName);
  }

  Future<void> closeBox(Box box) async {
    await box.close();
  }
}

class HiveCreateService extends HiveService {
  Future<void> create(String boxName, String key, dynamic value) async {
    var box = await openBox(boxName);
    await box.put(key, value);
    await closeBox(box);
  }
}

class HiveReadService extends HiveService {
  Future<dynamic> read(String boxName, String key) async {
    var box = await openBox(boxName);
    var value = box.get(key);
    await closeBox(box);
    return value;
  }
}

class HiveUpdateService extends HiveService {
  Future<void> update(String boxName, String key, dynamic value) async {
    var box = await openBox(boxName);
    await box.put(key, value);
    await closeBox(box);
  }
}

class HiveDeleteService extends HiveService {
  Future<void> delete(String boxName, String key) async {
    var box = await openBox(boxName);
    await box.delete(key);
    await closeBox(box);
  }
}

在這個範例中,我們首先定義了一個 HiveService 基礎類別,它包含了開啟和關閉 box 的方法。然後,我們為每個 CRUD 操作定義了一個繼承自 HiveService 的類別,每個類別都有一個對應的方法來執行該操作。

你可以在需要的地方創建這些類別的實例並呼叫它們的方法。例如,你可以在一個按鈕的點擊事件中呼叫 HiveCreateService().create(‘myBox’, ‘myKey’, ‘myValue’) 來創建一個新的鍵值對。

Box可以存放的對象

var box = await Hive.openBox('myBox');

// 儲存字串
await box.put('myString', 'Hello, World!');

// 儲存數字
await box.put('myNumber', 42);

// 儲存布林值
await box.put('myBool', true);

// 儲存列表
await box.put('myList', [1, 2, 3]);

// 儲存地圖
await box.put('myMap', {'key': 'value'});

await box.close();

深入Box - BoxCollection

BoxCollections 是一組可以與普通盒子類似使用的盒子,除了它們極大地提高了網路速度。它們支援開啟和關閉集合中的所有框,立即更有效地將資料儲存在網路上的索引資料庫中。

// 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<Map>('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<String> of all keys
  final allCatKeys = await catsBox.getAllKeys();
  print(allCatKeys);

  // Returns a Map<String, 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,
  );

這段程式碼展示了如何使用 BoxCollection 來管理 Hive 資料庫中的多個 Box。以下是該程式碼的詳細解釋:

首先,我們使用 BoxCollection.open 方法來創建一個 BoxCollection。這個方法需要兩個參數:資料庫的名稱和一組 Box 的名稱。在這個例子中,我們創建了一個名為 “MyFirstFluffyBox” 的資料庫,並在其中創建了兩個 Box:’cats’ 和 ‘dogs’。

然後,我們使用 collection.openBox 方法來開啟一個 Box。在這個例子中,我們開啟了 ‘cats’ 這個 Box。

接著,我們使用 catsBox.put 方法來在 ‘cats’ 這個 Box 中儲存一些資料。我們儲存了兩個鍵值對:’fluffy’ 和 ‘loki’,它們的值都是一個包含 ‘name’ 和 ‘age’ 的 Map。

然後,我們使用 catsBox.get 方法來讀取 ‘cats’ 這個 Box 中的資料。我們讀取了 ‘loki’ 這個鍵的值,並將它印出來。

我們也使用 catsBox.getAll、catsBox.getAllKeys 和 catsBox.getAllValues 方法來讀取 ‘cats’ 這個 Box 中的所有資料。

然後,我們使用 catsBox.delete 和 catsBox.deleteAll 方法來刪除 ‘cats’ 這個 Box 中的一些資料。

我們也使用 catsBox.clear 方法來清空 ‘cats’ 這個 Box。

最後,我們使用 collection.transaction 方法來執行一個交易。在這個交易中,我們再次在 ‘cats’ 這個 Box 中儲存了一些資料。使用交易可以提高寫入操作的效能,因為它可以一次性地將多個操作寫入到資料庫中。


Last update : 13 novembre 2024
Created : 13 novembre 2024

Comments

Comments