Hive in Flutter

为 Zemin 伊斯坦布尔演示制作

基本上,该应用程序将基本数据类型和自定义生成的数据类保存到本地存储中。

入门

依赖项?

dependencies:
  hive_flutter: ^1.1.0 //add this line

dev_dependencies:
  build_runner: ^2.2.1 //add this line
  hive_generator: ^1.1.3 //add this line
  • hive_flutter

提供对本地存储的操作。

  • build_runner

提供一种使用 Dart 代码生成文件的具体方法。

  • hive_generator

为几乎任何类提供 TypeAdapters 的自动生成。

项目架构输出

.
├── lib                  
    ├── core
        └── service
            ├── cache
                ├── base_cache_manager.dart
                └── cache_enums.dart   
    ├── model
        ├── todo_model.dart
        └── todo_model.g.dart
    └── product
        └── todo
            ├── todo_service.dart
            └── todo_view.dart
└── main.dart

基本函数和 Hive 类

基本函数

  • 初始化 Hive
  await Hive.initFlutter();
  • 打开 Hive Box

Future<void> boxInit() async {
  await Hive.openBox(boxName);
}
  • 使用自动递增键向 Box 添加项

Future<void> addItemWithAutoIncrementKey(T item) async {
  await _box!.add(item);
}
  • 使用自定义键向 Box 添加项

Future<void> addItemWithCustomKey(dynamic key, T item) async {
  await _box!.put(key, item);
}
  • 从 Box 获取项

T? getItem(dynamic key) {
  return _box!.get(key);
}
  • 从 Box 删除项

Future<void> removeItem(dynamic key) async {
  await _box!.delete(key);
}
  • 清空 Box

Future<void> clearBox() async {
  await _box!.clear();
}
  • 关闭 Box

Future<void> closeBox() async {
  await _box!.close();
}

Hive 类

  • 类架构

import 'package:hive_flutter/adapters.dart';
part 'todo_model.g.dart';

@HiveType(typeId: 1)
class Todo {
  @HiveField(0)
  int? userId;
  @HiveField(1)
  int? id;
  @HiveField(2)
  String? title;
  @HiveField(3)
  bool? completed;

  Todo({this.userId, this.id, this.title, this.completed});

  Todo.fromJson(Map<String, dynamic> json) {...}
  Map<String, dynamic> toJson() {...}
}
  • 生成 Part 文件命令
flutter pub run build_runner build

从泛型缓存管理器创建管理器

  • 初始化

final BaseCacheManager<Todo> _todoCacheManager = BaseCacheManager<Todo>(boxName: CacheBoxNames.todo);
Future<void> serviceInit() async {
  await _todoCacheManager.boxInit();
}

用法 ?

当管理器生成并初始化后,它就可以访问和使用泛型缓存管理器函数。

await _todoCacheManager.boxInit();
_todoCacheManager.getItemList();
await _todoCacheManager.addItemList(items);
await _todoCacheManager.clearBox();
...

来源

Hive 文档

GitHub

查看 Github