hiveMap框

hrysbysz  于 2021-06-24  发布在  Hive
关注(0)|答案(1)|浏览(417)

我在搜索,没有找到任何关于这个主题的东西。我想问,是否有任何Map器或自动Map为Hive盒或什么正确的方式来MapHive中的盒子?例如,我有:

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});
}

非常感谢您的回答!

bqujaahr

bqujaahr1#

一般建议你看一下官方文件,因为这些文件通常都有答案。在本例中,您可以查看配置单元文档,其中还说明了充分利用它所必需的依赖关系。
由于有些信息/改进没有很好地记录,我将给您一些关于如何管理配置单元的示例(我在以下代码块中编写了注解):
首先,我们声明一个类,该类表示我们的自定义对象,该对象应持久化在其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;

  ...
}

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


# 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');

希望这就是你要找的。

相关问题