Could not generate 'fromJson' code for custom model using freezed build

733 views Asked by At

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.

2

There are 2 answers

0
Ian Cho On BEST ANSWER

self answering.

import 'package:freezed_annotation/freezed_annotation.dart';

@JsonSerializable() //<-- added
class Post {
  final int userId;
  final String title;

  Post(this.userId, this.title);

  Post.fromJson(Map<String, dynamic> map)  // <-- modified name.
      : userId = map["userId"],
        title = map["title"];

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['userId'] = userId;
    data['id'] = id;
    data['title'] = title;
    data['body'] = body;
    return data;
  }
}

I added annotation @JsonSerializable() on my custom model. When code generate using build_runner, generated method name is fromJson so, modified it.

0
Hasan Karli On

Or you can use with freezed

import 'package:freezed_annotation/freezed_annotation.dart';

part 'post.freezed.dart';
part 'post.g.dart';

@freezed
class Post with _$Post {

  const factory Post({
    required int userId,
    required String title,
  }) = _Post;

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