admin管理员组

文章数量:1353814

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.

本文标签: flutterInclude UniqueKey in freezed classStack Overflow