rrousselGit / freezed

Code generation for immutable classes that has a simple syntax/API without compromising on the features.
https://pub.dev/packages/freezed
1.91k stars 235 forks source link

Can't generate class with records #909

Open ChaserVasya opened 1 year ago

ChaserVasya commented 1 year ago

Describe the bug Freezed can't generate class with records.

To Reproduce What is currently working:

@freezed
class DTO with _$DTO {
  const factory DTO({
    int? id,
    required NestedDTO nested,
  }) = _DTO;

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

@freezed
class NestedDTO with _$NestedDTO {
  factory NestedDTO({
    required String title,
  }) = _NestedDTO;

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

I want to reduce nested classes by records:

@freezed
class DTO with _$DTO {
  const factory DTO({
    int? id,
    required ({
      String title,
    }) nested,
  }) = _DTO;

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

When generated, a bug appears: Null check operator used on a null value

Expected behavior I want created objects by each of the snippets to be successfully generated and have the following API.

dto.id; //int?
dto.nested.title; //String
debkanchan commented 1 year ago

Desperately need records in freezed

KoheiKanagu commented 1 year ago

I was able to generate it with freezed: ^2.3.5 with no problems.

The complete code for the DTO class is here.

import 'package:freezed_annotation/freezed_annotation.dart';

part 'dto.freezed.dart';
part 'dto.g.dart';

@freezed
class DTO with _$DTO {
  const factory DTO({
    int? id,
    required ({
      String title,
    }) nested,
  }) = _DTO;

  factory DTO.fromJson(Map<String, dynamic> json) => _$DTOFromJson(json);
}
SunlightBro commented 1 year ago

Could be that by using analyzer 5.13.0, records now get generated correctly. But 2.3.5 was only a temporary hotfix to prevent generation of InvalidType. I never added any tests for record to check if copyWith, equals, ... are generated correctly.

debkanchan commented 1 year ago

After upgrading to latest freezed version it works now

khangpt commented 5 months ago
const factory MyClass.edit(
    String code, {
    List<(Uint8List, String)>? imgs,
  }) = _Edit;

For my usecase, I upgrade to latest of freezed package, but keep version of freezed_annotation is v2.2.0

freezed_annotation: ^2.2.0

It will build fine. If upgrade freezed_annotation to latest version, it reach the error of records experiment