flutterflutter-hive

HiveError: Cannot write, unknown type: Duration. Did you forget to register an adapter?


after I added this Duration field in this model

import 'package:hive_flutter/hive_flutter.dart';
part 'workout_record.g.dart';

@HiveType(typeId: 3)
class WorkOutRecordModel {
  @HiveField(1)
  final String icon;
  @HiveField(2)
  final String workoutName;
  @HiveField(3)
  final DateTime dateTime;
  @HiveField(5)
  final Duration duration;

  WorkOutRecordModel({
    required this.dateTime,
    required this.icon,
    required this.workoutName,
   required this.duration,
  });
}

I'm getting this error *Unhandled Exception: HiveError: Cannot write, unknown type: Duration. Did you forget to register an adapter? *

i deleted the workout_record.g.dart and recreated after I added the duration field. I already registered the adapter so wondering what's going wrong.


Solution

  • You need to create a TypeAdapter for that.

    This uses the milliseconds of a duration to store it:

    class DurationAdapter extends TypeAdapter<Duration> {
      @override
      final typeId = 0; // Put an ID you didn't use yet.
    
      @override
      Duration read(BinaryReader reader) {
        return Duration(milliseconds: reader.readInt());
      }
    
      @override
      void write(BinaryWriter writer, Duration obj) {
        writer.writeInt(obj.inMilliseconds);
      }
    }
    

    And don't forget to register it

    void main() {
      Hive
        ..registerAdapter(WorkOutRecordModelAdapter())
        ..registerAdapter(DurationAdapter()); // <- Register your duration adapter.
    }