Flutter Hive store color

Issue

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?

Solution

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);

Answered By – Loren.A

Answer Checked By – David Marino (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.