Flutter Hive存储颜色



我需要将颜色存储在我的Hive数据库中,以便在我的电子商务应用程序中检索,它给了我下面的错误,说我需要制作一个适配器,有人能告诉我如何制作彩色适配器吗?

part 'items_model.g.dart';
@HiveType(typeId: 0)
class Item {
@HiveField(0)
final String name;
@HiveField(1)
final double price;
@HiveField(2)
final String? description;
@HiveField(3)
var image;
@HiveField(4)
final String id;
@HiveField(5)
final String shopName;
@HiveField(6)
final List<Category> category;
@HiveField(7)
Color? color;
@HiveField(8)
int? quantity;
Item({
required this.category,
required this.image,
required this.name,
required this.price,
this.description,
required this.id,
required this.shopName,
this.color,
required this.quantity,
});

}

有人知道如何生成或创建"颜色适配器"吗?因为我不了解

E/flutter ( 4621): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: HiveError: Cannot write, unknown type: MaterialColor. Did you forget to register an adapter?

我认为这里最简单的方法是存储颜色的int值。

下面是一个例子。

final colorValue = Colors.blue.value; // colorValue is an integer here

所以你的Hive颜色可以像这个一样存储

@HiveField(7)
int? colorValue;

然后,在你的应用程序中,当你从存储中创建颜色时,它会是这样的。

final item = Item(...however you initialize your Item);
final color = Color(item.colorValue);

基于@Cryptozord和@Loren之前的回答。一个人可以简单地为彩色编写特定的适配器

import 'package:flutter/cupertino.dart';
import 'package:hive/hive.dart';
class ColorAdapter extends TypeAdapter<Color> {
@override
final typeId = 221;
@override
Color read(BinaryReader reader) => Color(reader.readUint32());
@override
void write(BinaryWriter writer, Color obj) => writer.writeUint32(obj.value);
}

并记得向注册您的适配器

Hive.registerAdapter(ColorAdapter());

确保你的typeId没有被其他型号的占用

现在你可以使用了

@HiveField(7)
Color? colorValue;

我对此困惑了一整天,并想出了如何做到这一点。您应该手动创建适配器,如下所示:

class ItemAdapter extends TypeAdapter<Item> {
@override
final typeId = 0;
@override
ThemeState read(BinaryReader reader) {
return Item(
color: Color(reader.readUint32()),
//the rest of the fields here
);
}
@override
void write(BinaryWriter writer, ThemeState obj) {
writer.writeUint32(obj.color.value);
writer.writeString(obj.name);
//the rest of the fields here
}
}

由于Int32值的范围仅为-2147483648到2147483647,而无符号整数为0到4294967295,因此颜色需要保存并写入为Uint32值。Color((的整数值可以超过2147483647。如果不使用Uint32,那么您的值将无法正确存储,而奇怪的颜色将被保存。

最新更新