如何保存List< Object>并使用Hive检索? [英] How to save a List<Object> and retrieve using Hive?
问题描述
我有一个墙纸应用程序,它使用Firestore存储墙纸。
I have a Wallpaper App and it uses Firestore to store the wallpapers.
我想使用Hive存储云Firestore中的墙纸列表,但如何保存墙纸列表并在以后检索?
I want to use Hive to store a list of wallpapers from cloud firestore but how to save the List of Wallpapers and retrieve it later?
当我尝试保存列表时出现此错误:
When I try to save the list I get this error:
E / flutter(9995):[错误:flutter / shell / common / shell.cc(199)] Dart错误:未处理的异常:
E / flutter(9995):HiveError:无法写入,未知类型:墙纸。您忘记注册适配器了吗?
E/flutter ( 9995): [ERROR:flutter/shell/common/shell.cc(199)] Dart Error: Unhandled exception: E/flutter ( 9995): HiveError: Cannot write, unknown type: Wallpaper. Did you forget to register an adapter?
代码:
class Wallpaper extends HiveObject {
String date;
String url;
Wallpaper();
}
static Future<void> addWallpapers({@required String boxName, @required List<Wallpaper> wallpapers}) async {
var box = await Hive.openBox(boxName);
box.put(boxName, wallpapers);
print("WALLPAPER ADICIONADO NO HIVE!");
}
static Future<List<Wallpaper>> getWallpapers({@required String boxName}) async {
var box = await Hive.openBox(boxName);
List<Wallpaper> wallpapers = box.get("latest");
return wallpapers;
}
推荐答案
您有使用@HiveType()注释对象。并且必须注册您的对象Hive.registerAdapter(WallpaperAdapter(),0);。
You have to anotate your object with @HiveType(). And have to register your object Hive.registerAdapter(WallpaperAdapter(), 0);.
但是,您是否有 part'wallpaper.g .dart';
生成所需的代码?
And yet, do you have part 'wallpaper.g.dart';
to generate the needed code?
编辑:
首先导入对pubspec的依赖项:
EDITED: First of all import the dependencies on your pubspec:
dependencies:
hive: ^[version]
hive_flutter: ^[version]
dev_dependencies:
hive_generator: ^[version]
build_runner: ^[version]
Hive.registerAdapter(MyObjectAdapter(),0);
您应该放入 main.dart
函数。在runApp之前
The Hive.registerAdapter(MyObjectAdapter(), 0);
you should put inside your main.dart
function. Right before runApp
您的HiveObject应该具有这样的注释:
Your HiveObject should have annotations like that:
@HiveType()
class Person extends HiveObject {
@HiveField(0);
String name;
@HiveField(1);
int age;
}
将此命令放在您的进口 part'person附近。 g.dart';
并在您的终端上运行代码生成。 flutter包pub run build_runner build
。
Put this command near your imports part 'person.g.dart';
and run the code generation on your terminal. flutter packages pub run build_runner build
.
具有代码生成功能的Hive函数,因此此命令将生成您需要的文件
Hive function with code generation, so this command will generate the file you need
这篇关于如何保存List< Object>并使用Hive检索?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!