问题
I have a Wallpaper App and it uses Firestore to store the wallpapers.
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): [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?
Code:
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;
}
回答1:
You have to anotate your object with @HiveType(). And have to register your object Hive.registerAdapter(WallpaperAdapter(), 0);.
And yet, do you have part 'wallpaper.g.dart'; to generate the needed code?
EDITED: First of all import the dependencies on your pubspec:
dependencies:
hive: ^[version]
hive_flutter: ^[version]
dev_dependencies:
hive_generator: ^[version]
build_runner: ^[version]
The Hive.registerAdapter(MyObjectAdapter(), 0); you should put inside your main.dart function. Right before runApp
Your HiveObject should have annotations like that:
@HiveType()
class Person extends HiveObject {
@HiveField(0);
String name;
@HiveField(1);
int age;
}
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 function with code generation, so this command will generate the file you need
来源:https://stackoverflow.com/questions/59413228/flutter-how-to-save-a-listobject-and-retrieve-using-hive