Flutter Hive store color


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 {
  final String name;
  final double price;
  final String? description;
  var image;
  final String id;
  final String shopName;
  final List<Category> category;
  Color? color;
  int? quantity;
    required this.category,
    required this.image,
    required this.name,
    required this.price,
    required this.id,
    required this.shopName,
    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

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. Required fields are marked *