I made a class using freezed in flutter like this.
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:flutter/foundation.dart';
import 'package:my_project/src/models/post.dart';
part 'post_state.freezed.dart';
part 'post_state.g.dart';
@freezed
class PostState with _$PostState {
factory PostState({
@Default(1) int page,
required List<Post> posts, // <-- error
@Default(false) bool isLoading,
}) = _PostState;
const PostState._();
factory PostState.fromJson(Map<String, dynamic> json) =>
_$PostStateFromJson(json);
}
class Post {
final int userId;
final String title;
Post(this.userId, this.title);
Post.fromJsonMap(Map<String, dynamic> map)
: userId = map["userId"],
title = map["title"];
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['userId'] = userId;
data['title'] = title;
return data;
}
}
Then, generate code
> flutter pub run build_runner build --delete-conflicting-outputs
This is the result
Could not generate `fromJson` code for `posts` because of type `Post`.
package:my_project/src/state/post_state.freezed.dart:169:18
╷
169 │ List<Post> get posts {
│ ^^^^^
╵
It looks related json_serializable. If I'm not using custom model, it works very well.
any advice?
Thanks.
self answering.
I added annotation @JsonSerializable() on my custom model. When code generate using build_runner, generated method name is fromJson so, modified it.