flutterflutter-hive

Flutter Hive model have enum type but not able to put/set value in enum with hive-field


I want a hivemodel class which is contain enum as field but hive is not able to put set value.

CONTACTTYPE is enum:

click here

click here

@freezed
@HiveType(typeId: 7, adapterName: "FriendGroupEntityAdapter")
@freezed

class FriendsGroupEntity with _$FriendsGroupEntity {

  const factory FriendsGroupEntity({
 @HiveField(0)  int userId,
  @HiveField(1)  @Default(CONTACTTYPE.loop) CONTACTTYPE contactType,
  @HiveField(2)   String contact,
  @HiveField(3)   int id,
  @HiveField(4)   int value,
  @HiveField(5)   int value2,
  @HiveField(6)   int value3,
  @HiveField(7)   int value7,
});

Here CONTACTTYPE.loop is an enum and I want to store it into hive, and got an error which I attach.

Is there any way for enum in hive?


Solution

  • Please follow this approach

    import 'package:hive/hive.dart';
        
        part 'myrepresentation.g.dart';
        
        @HiveType(typeId: 1)
        class FriendsGroupEntity extends HiveObject {
          @HiveField(0)
          final String id;
        
          @HiveField(1)
          final Foo foo;
          MyRepresentation({required this.id, required this.foo});
        }
        
        @HiveType(typeId: 2)
        enum Foo {
          @HiveField(0)
          foo,
          @HiveField(1)
          bar,
        }
    

    check this reference link