flutterhiveadapter

Type Adapter for Offset in hive flutter


I have this class called DrawLine and I have generated the adapter class

import 'dart:ui';
import 'package:hive/hive.dart';

part 'draw_line.g.dart';

@HiveType(typeId: 0)
class DrawnLine extends HiveObject{
  @HiveField(0)
  final List<Offset> path;

  @HiveField(1)
  final Color color;

  @HiveField(2)
  final double width;

  @HiveField(3)
  final bool isEraser;
  DrawnLine(this.path, this.color, this.width, this.isEraser);
}

When I try to save list of DrawLine objects, there is an error which indicates hive does not recognize the type Offset in the object.

Which means that I have to in turn make an adapter for Offset too but I don't know how to go about it. Any help will be much appreciated.


Solution

  • Offset is not supported in Hive. Hive only supports List, Map, DateTime and Uint8List.

    To support other objects you have to register a TypeAdapter which converts the object from and to binary form.

    In your case, to support a Offset you have to create its own adapter and register it in the main method.

    void main() async {
      await Hive.initFlutter();
      Hive.registerAdapter(OffsetAdapter());
      await Hive.openBox<Offset>('offsetBox');
    }
    

    Check the Offset Adapter code:

    import 'package:flutter/material.dart';
    import 'package:hive_flutter/hive_flutter.dart';
    
    class OffsetAdapter extends TypeAdapter<Offset> {
      @override
      final typeId = 0;
    
      @override
      Offset read(BinaryReader reader) {
        final value = reader.readMap();
        final dx = value['dx'] as double;
        final dy = value['dy'] as double;
    
        return Offset(dx, dy);
      }
    
      @override
      void write(BinaryWriter writer, Offset obj) {
        writer.writeMap({
          'dx': obj.dx,
          'dy': obj.dy,
        });
      }
    }
    

    To open offsetBox:

    final box = Hive.box<Offset>('offsetBox');