You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter ObjectBox嵌套关系报错:'target' setter未定义

Flutter ObjectBox嵌套关系赋值报错:'target' setter未定义的解决办法

你遇到的错误核心原因是:UserProfileModel中的currentLocation和homeTown字段不是ObjectBox的ToOne关联类型,而是直接声明为普通的LocationModel?对象引用,因此没有target setter可以调用。而userModel是ToOne<UserModel>类型,符合ObjectBox的关联字段规范,所以能正常使用.target赋值。

代码问题分析

看你的模型定义:

  • UserProfileModel里的currentLocation、homeTown是final LocationModel?类型,这只是普通对象引用,不受ObjectBox关联管理,自然没有target属性。
  • LocationModel里的currentLocation、homeTown是ToOne<UserProfileModel>,这是单向关联,但UserProfileModel没有对应的ObjectBox关联字段匹配,导致你赋值时触发错误。

解决方案:修正字段类型为ObjectBox关联类型

把UserProfileModel中的currentLocation和homeTown改成ToOne<LocationModel>类型,同时保留@Transient避免JSON序列化冲突(因为你用了@JsonKey注解),调整后的代码如下:

class UserProfileModel extends Equatable {
  @Id()
  int id;
  @JsonKey(name: 'avatar_url')
  final String? avatarUrl;
  
  // 替换为ToOne<LocationModel>,保留@Transient跳过JSON序列化
  @JsonKey(name: 'current_location')
  @Transient()
  final currentLocation = ToOne<LocationModel>();
  
  @JsonKey(name: 'home_town')
  @Transient()
  final homeTown = ToOne<LocationModel>();
  
  final userModel = ToOne<UserModel>();
  
  UserProfileModel({this.id = 0});

  // 可选:添加JSON转模型的构造方法,处理关联对象赋值
  UserProfileModel.fromJson(Map<String, dynamic> json) : id = 0 {
    avatarUrl = json['avatar_url'];
    // 解析JSON中的LocationModel后,赋值给target
    if (json['current_location'] != null) {
      currentLocation.target = LocationModel.fromJson(json['current_location']);
    }
    if (json['home_town'] != null) {
      homeTown.target = LocationModel.fromJson(json['home_town']);
    }
  }

  @override
  List<Object?> get props => [id, avatarUrl, currentLocation.target, homeTown.target, userModel.target];
}

可选:配置双向关联

如果需要从LocationModel反向访问对应的UserProfileModel,可以在LocationModel的ToOne字段上添加@Backlink注解,指定反向关联字段:

class LocationModel extends Equatable {
  @Id()
  int id;
  final String? city;
  final String? country;
  final String? latitude;
  final String? longitude;
  
  LocationModel({this.id = 0, this.city, this.country, this.latitude, this.longitude});

  // 添加@Backlink绑定反向关联字段
  @Backlink()
  final currentLocation = ToOne<UserProfileModel>();
  
  @Backlink()
  final homeTown = ToOne<UserProfileModel>();

  @override
  List<Object?> get props => [id, city, country, latitude, longitude, currentLocation.target, homeTown.target];
}

赋值方式说明

修正后,你就可以像操作userModel一样给关联字段赋值:

// 假设已有location实例
profileModel.currentLocation.target = locationInstance;
profileModel.homeTown.target = anotherLocationInstance;

内容的提问来源于stack exchange,提问作者Joseph Barasa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 15:56:08