如何用自定义类型初始化Objectbox实体?

2024-02-18

我正在使用 Objectbox (1.3.0) 在 Flutter 上构建我的数据库。

我尝试创建一个由自定义类型(枚举)组成的实体,如下所示:

type_enum.dart

/// Type Enumeration.
enum TypeEnum { one, two, three }

方法.dart

@Entity()
class Method {
  /// ObjectBox 64-bit integer ID property, mandatory.
  int id = 0;

  /// Custom Type. 
  TypeEnum type;

  /// Constructor.
  Method(this.type);

  /// Define a field with a supported type, that is backed by the state field.
  int get dbType {
    _ensureStableEnumValues();
    return type.index;
  }

  /// Setter of Custom type. Throws a RangeError if not found.
  set dbType(int value) {
    _ensureStableEnumValues();
    type = TypeEnum.values[value];
  }

  void _ensureStableEnumValues() {
    assert(TypeEnum.one.index == 0);
    assert(TypeEnum.two.index == 1);
    assert(TypeEnum.three.index == 2);
  }
}

前面的代码导致此错误(运行此命令后dart run build_runner build :


[WARNING] objectbox_generator:resolver on lib/entity/method.dart:
  skipping property 'type' in entity 'Method', as it has an unsupported type: 'TypeEnum'
[WARNING] objectbox_generator:generator on lib/$lib$:
Creating model: lib/objectbox-model.json
[SEVERE] objectbox_generator:generator on lib/$lib$:

Cannot use the default constructor of 'Method': don't know how to initialize param method - no such property.

我想通过构造函数参数给定类型来构造方法。有什么问题吗?

如果我删除构造函数,我应该在类型字段前面添加后期标识符。我不想这样做。可能是吧,我不明白。我还没有找到任何例子。


我的解决方案:

方法.dart

@Entity()
class Method {
  /// ObjectBox 64-bit integer ID property, mandatory.
  int id = 0;

  /// Custom Type. 
  late TypeEnum type;

  /// Constructor.
  Method(int dbType){
     this.dbType = dbType;
  }

  /// Define a field with a supported type, that is backed by the state field.
  int get dbType {
    _ensureStableEnumValues();
    return type.index;
  }

  /// Setter of Custom type. Throws a RangeError if not found.
  set dbType(int value) {
    _ensureStableEnumValues();
    type = TypeEnum.values[value];
  }
}

为了使 ObjectBox 能够构造从数据库读取的对象,实体必须有一个默认构造函数 https://docs.objectbox.io/entity-annotations#objectbox-database-persistence-with-entity-annotations或参数名称与属性匹配的构造函数。

例如,要在这种情况下获取默认构造函数,请将参数设置为可选并提供默认值:

Method({this.type = TypeEnum.one});

或者添加一个默认构造函数,并将需要类型的构造函数设置为命名构造函数:

Method() : type = TypeEnum.one;
Method.type(this.type);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何用自定义类型初始化Objectbox实体? 的相关文章

随机推荐