一般建议你看一下官方文档,因为那些通常都有所有答案。在这种情况下,您可以查看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');
希望这就是您想要的。