Flutter 中的 Hive 映射框

Posted

技术标签:

【中文标题】Flutter 中的 Hive 映射框【英文标题】:Hive mapping boxes in Flutter 【发布时间】:2021-02-14 23:19:29 【问题描述】:

我正在搜索,但没有找到有关此主题的任何内容。我想问一下 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);

【问题讨论】:

【参考方案1】:

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

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

首先,我们声明一个代表我们的自定义对象的类,该对象应保留在其 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');

希望这就是您想要的。

【讨论】:

以上是关于Flutter 中的 Hive 映射框的主要内容,如果未能解决你的问题,请参考以下文章

Flutter HiveDB 在 FutureBuilder 上使用框

Flutte VS RN

Flutter 离线数据方案 Flutter_Data 包

Flutter 离线数据方案 Flutter_Data 包

flutte学习-编译模式

flutte学习-编译模式