最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

flutter - Include UniqueKey in freezed class - Stack Overflow

programmeradmin2浏览0评论

Suppose this were my freezed class:

@freezed
class User with _$User {
  factory User({
    required String uuid,
    required UniqueKey key,
    @Default('') String name,
  }) = _User;

  factory User.initial() => User(
        uuid:  '',
        key: UniqueKey(),
      );

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

This throws an error Could not generate fromJson code for key.

So I tried

factory User.fromJson(Map<String, dynamic> json) =>
    _$UserFromJson({...json, 'key': UniqueKey()});

but this is not valid either. It says "to support UniqueKey you can use JsonConverter"- I don't understand how to.

I also tried adding @JsonKey(includeFromJson: false, includeToJson: false) but that throws another error.

Suppose this were my freezed class:

@freezed
class User with _$User {
  factory User({
    required String uuid,
    required UniqueKey key,
    @Default('') String name,
  }) = _User;

  factory User.initial() => User(
        uuid:  '',
        key: UniqueKey(),
      );

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

This throws an error Could not generate fromJson code for key.

So I tried

factory User.fromJson(Map<String, dynamic> json) =>
    _$UserFromJson({...json, 'key': UniqueKey()});

but this is not valid either. It says "to support UniqueKey you can use JsonConverter"- I don't understand how to.

I also tried adding @JsonKey(includeFromJson: false, includeToJson: false) but that throws another error.

Share Improve this question asked Mar 31 at 22:46 user3808307user3808307 1,47312 gold badges63 silver badges114 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

Option 1. Remove

  factory User.fromJson(Map<String, dynamic> json) =>
      _$UserFromJson(json);

from your freezed class, if you don't need the object to be serializable to json.

Option 2. If you do need it to be serializable to json then you can't use UniqueKey. You can instead generate a unique number and put that in the freezed class, and then use ValueKey(that number) to get a key.

发布评论

评论列表(0)

  1. 暂无评论