ネストしたFreezdクラスを作ろうとしたができなかった?
Tips💡
ネストしたFreezdクラスを作ろうとしたができなかった???
なぜだ???
[error code]
The method '_
[before]
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:flutter/foundation.dart';
part 'relationships.freezed.dart';
part 'relationships.g.dart';
// flutter pub run build_runner watch --delete-conflicting-outputs
class Relationships with _$Relationships {
const factory Relationships({
(0) int followingId,
(FollowingState(id: 0, name: '')) FollowingState followings,
}) = _Relationships;
factory Relationships.fromJson(Map<String, Object?> json)
=> _$RelationshipsFromJson(json);
}
class FollowingState with _$Person {
const factory FollowingState({
(0) int id,
('') String name,
}) = _Person;
factory FollowingState.fromJson(Map<String, Object?> json)
=> _$FollowingStateFromJson(json);
}
[after]
@JsonSerializable()
をつけたら解決!
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:flutter/foundation.dart';
part 'follow.freezed.dart';
part 'follow.g.dart';
// flutter pub run build_runner watch --delete-conflicting-outputs
class Relationships with _$Relationships {
const factory Relationships({
(0) int followingId,
(FollowingState(id: 0, name: '')) FollowingState followings,
}) = _Relationships;
factory Relationships.fromJson(Map<String, Object?> json)
=> _$RelationshipsFromJson(json);
}
()
class FollowingState with _$FollowingState {
const factory FollowingState({
(0) int id,
('') String name,
}) = _FollowingState;
factory FollowingState.fromJson(Map<String, dynamic> json) => _$FollowingStateFromJson(json);
}
AIによると?
@JsonSerializable()アノテーションは、json_serializableパッケージがJSONのシリアライズとデシリアライズのためのコードを自動的に生成するための指示です。このアノテーションがないと、json_serializableはそのクラスに対してコードを生成しないため、fromJsonやtoJsonのようなメソッドが定義されません。 具体的には、@JsonSerializable()アノテーションがついたクラスに対して、json_serializableは以下のメソッドを生成します:
fromJson(Map<String, dynamic> json):JSONマップを受け取り、それをクラスの新しいインスタンスに変換します。
toJson():クラスのインスタンスをJSONマップに変換します。
これらのメソッドは、JSONとDartオブジェクト間の変換を容易にするために必要です。したがって、@JsonSerializable()アノテーションがないと、これらのメソッドが生成されず、JSONのシリアライズとデシリアライズができなくなります。
最後に
以前参考にしたコード使ってみたが、ダメだった😅
詳しく理解しなければならないなと思った。toJson, fromJsonの生成がうまくいかなかったのか....
どうすれば良い感じのネストしたクラスかけるのか...
と思ったらできた???
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:flutter/foundation.dart';
part 'follow.freezed.dart';
part 'follow.g.dart';
// flutter pub run build_runner watch --delete-conflicting-outputs
class Relationships with _$Relationships {
const factory Relationships({
(0) int followingId,
(FollowState(id: 0, name: '')) FollowState followings,
}) = _Relationships;
factory Relationships.fromJson(Map<String, Object?> json)
=> _$RelationshipsFromJson(json);
}
class FollowState with _$FollowState {
const factory FollowState({
(0) int id,
('') String name,
}) = _FollowState;
factory FollowState.fromJson(Map<String, dynamic> json) => _$FollowStateFromJson(json);
}
ニョロニョロが消えた???
Discussion