0

我正在搜索并没有找到有关此主题的任何内容。我想问一下 Hive 盒子是否存在任何映射器或自动映射器,或者在 Hive 中映射盒子的正确方法是什么?例如我有:

 class Company extends HiveObject {
  @HiveField(0)
  int id;

  @HiveField(1)
  String name;

  @HiveField(2)
  CompanyType type; //this is enum

  @HiveField(3)
  HiveList<Person> persons; 

  Person({this.id, this.name, this.type});
}
4

1 回答 1

2

通常建议您查看官方文档,因为这些文档通常都有所有答案。在这种情况下,您可以查看Hive 文档,该文档还说明了充分利用它所必需的依赖项。

由于一些信息/改进没有很好地记录,我会给你一些关于我如何管理 Hive 东西的例子(我在下面的代码块中写了评论):

首先,我们声明一个代表我们的自定义对象的类,该对象应该保存在它的 on 框中(就像你做的那样):

import 'package:hive/hive.dart';

/// We want to generate the class which is based on this one with its annotations which actually takes care of loading / writing this object later on (usually called just like the class itself with ".g." between name and extension (dart)
part 'connection.g.dart';

@HiveType(typeId: 0)
class Connection extends HiveObject {
  @HiveField(0)
  String name;

  ...
}

现在我们将在每次更新 Hive 类或添加新类时运行以下命令(终端/控制台):

# Making use of "--delete-conflicting-outputs" to create those generated classes by deleting the old ones instead of trying to update existing ones (usually the option we want)
flutter packages pub run build_runner build --delete-conflicting-outputs

一旦完成并且我们有了生成的类,我们需要注册它们以便稍后在我们的代码中加载它们:

/// Preferably we do this in the main function
void main() async {
  await Hive.initFlutter();

  /// Register all "Adapters" (which has just been generated via terminal)
  Hive.registerAdapter(ConnectionAdapter());

  /// Open Hive boxes which are coupled to HiveObjects
  await Hive.openBox<Connection>(
    'connections',
    /// Optional: just did that to avoid having too many dead entries
    compactionStrategy: (entries, deletedEntries) => deletedEntries > 50,
  );

  ...
}

完成所有这些后,我们现在可以安全轻松地访问这些盒子:

/// Where ever we are in our code / widget tree, we can now just access those boxes (note how we don't have to await this, it's not async since we opened the box in the main already)
Box<Connection> box = Hive.box<Connection>('connections');

希望这就是你要找的。

于 2020-11-02T10:35:26.433 回答