Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

combine freezed & hive

I'm searching for a solution to combine freezed and hive packages. For example like that:

@freezed
abstract class Person extends HiveObject with _$Person {
  @HiveType(typeId: 0)
  factory Person({@HiveField(0) String name, @HiveField(1) int age}) = _Person;
}

I know that this is not possible out of the box, but I think you know what I want to achieve. What would be the best way to implement freezed with hive?

The only solution that I can currently think of is to store the json-String which is generated by freezed in hive. But I hope there is a better solution.

like image 854
DennisSzymanski Avatar asked Feb 24 '20 20:02

DennisSzymanski


People also ask

What is freezed package?

The freezed package is a code generator for data classes and union classes that is robust and scalable. In addition, it allows the serialization and deserialization of JSON data.

Why we use freezed in flutter?

> freezed:- Freezed package is used to create the model. It's code generator for data-classes/unions/pattern-matching/cloning. > build_runner:- The build_runner package provides a concrete way of generating files using Dart code, outside of tools like the pub.

How do I extend my freezed class?

Freezed classes can neither be extended nor implemented.


1 Answers

yes, it is now possible, make sure your min version is hive_generator: ^0.7.2+1.

as an example you could write:

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

part 'immutable_class.freezed.dart';
part 'immutable_class.g.dart';

@freezed
abstract class ImmutableClass with _$ImmutableClass {
  @HiveType(typeId: 5, adapterName: 'ImmutableClassAdapter')
  const factory ImmutableClass({
    @JsonKey(name: 'id', required: true, disallowNullValue: true) @HiveField(0) int id,
    @HiveField(1) int someField1,
    @HiveField(2) String someField2,
  }) = _ImmutableClass;

  factory ImmutableClass.fromJson(Map<String, dynamic> json) => _$ImmutableClassFromJson(json);
}

the only disadvantage is that you should specify the name of your adaptor.

like image 180
mohammad Avatar answered Oct 03 '22 04:10

mohammad