I need to store colour in my Hive database to retrieve in my eCommerce Application, it gave me the error below saying that I need to make an adapter, can anyone tell me how to make a colour adapter?
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,
});
}
does anyone know how to generate or create Color Adapter? as I don't know-how
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?
I think the easiest thing to do here would be to store the int value of the color.
Here's an example.
final colorValue = Colors.blue.value; // colorValue is an integer here
So your Hive color could be stored like this
@HiveField(7)
int? colorValue;
Then, in your app when you're creating a color from storage it would look like this.
final item = Item(...however you initialize your Item);
final color = Color(item.colorValue);
Base on previous answers by @Cryptozord and @Loren.A one can simply just write specific adapter for color
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);
}
and remember to register your adapter with
Hive.registerAdapter(ColorAdapter());
make sure your typeId is not taken by other models
now you can use
@HiveField(7)
Color? colorValue;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With