freezed icon indicating copy to clipboard operation
freezed copied to clipboard

Add support for required constructor parameters that are ignored by freezes

Open TheFriendlyCoder opened this issue 10 months ago • 1 comments

Is your feature request related to a problem? Please describe. I am creating a class that will mostly map to a data class, encapsulating JSON response data from a REST API. However, the class will need to perform additional operations against the API in addition to storing the data. In order to perform these additional tasks the class needs to contain a reference to an HTTP session object, but this object is not intended to be serialized.

I've managed to get this mostly working by using some code that looks like this:

@freezed
class MyObj with _$MyObj {
  const MyObj._();

  const factory MyObj(
      {
      required String id,
      required String name,
      @JsonKey(includeFromJson: false, includeToJson: false) Session? session,
      }) = _MyObj;

factory MyObj.fromJson(Map<String, Object?> json, Session session) =>
      _$MyObjFromJson(json).copyWith(session: session);
}

The problem case arises when I try to make the session field required as in @JsonKey(includeFromJson: false, includeToJson: false) required Session? session. Doing so produces an error that looks something like this:

Cannot populate the required constructor argument: session. It is assigned to a field not meant to be used in fromJson.

Describe the solution you'd like I would like to be able to declare my class with a required field that must get populated during construction.

Describe alternatives you've considered I've tried to come up with a way to define the JSON data class portion as a base class, and then define a derived class that extends this one which adds the required session object, but I kept hitting problems revolving around construction (ie: no generative constructors on the base classes etc.)

Additional context N/A

TheFriendlyCoder avatar Apr 23 '24 22:04 TheFriendlyCoder

The Error you posted is from json_serializable, not freezed.

[SEVERE] json_serializable on lib/issue_1075.dart:

Cannot populate the required constructor argument: session. It is assigned to a field not meant to be used in fromJson.
package:freezed_issues/issue_1075.freezed.dart:126:9
    ╷
126 │   const _$MyObjImpl(
    │         ^^^^^^^^^^^
    ╵

json_serializable issues

SunlightBro avatar Apr 24 '24 10:04 SunlightBro

Indeed, that's a json-serializable issue. Sounds like you want it to support passing null to required parameters if excluded from JSON.

rrousselGit avatar Jul 08 '24 06:07 rrousselGit