1

When trying to convert, the Profile class is not converted correctly. Exited as the result of the toString () function.

Person.dart

import 'package:adminapp/domains/Test/Profile.dart';
import 'package:freezed_annotation/freezed_annotation.dart';

part 'Person.freezed.dart';
part 'Person.g.dart';

@freezed
class Person with _$Person {
  factory Person({
    String? id,
    Profile? profile,
  }) = _Person;

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

Profile.dart

import 'package:freezed_annotation/freezed_annotation.dart';

part 'Profile.freezed.dart';
part 'Profile.g.dart';

@freezed
class Profile with _$Profile {
  factory Profile({
    DateTime? bDay,
    String? hob,
    String? rel,
  }) = _Profile;

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

main.dart

import 'package:adminapp/domains/Test/Person.dart';
import 'package:adminapp/domains/Test/Profile.dart';

void main(List<String> args) {
  Person p = Person(
      id: '4',
      profile: Profile(
        bDay: DateTime.now(),
        hob: "123",
        rel: 'asd',
      ));
  print(p.toJson());
}

output:

{id: 4, profile: Profile(bDay: 2021-07-28 08:42:51.708857, hob: 123, rel: asd)}

But it's not json format! Profile class convert dont corect! And I cant save it to firestore!

1 Answers1

2

Your desired valid json string:

{id: 4, profile: {bDay: 2022-08-08T14:54:11.781502, hob: 123, rel: asd}}

From documentation:

In order to serialize nested lists of freezed objects, you are supposed to either specify a @JsonSerializable(explicitToJson: true) or change explicit_to_json inside your build.yaml file.

After in generated class will be one small change, pls see the pic below:

enter image description here

Andrew Piterov
  • 340
  • 3
  • 12