1

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 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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);
  
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.