json_serializable.dart icon indicating copy to clipboard operation
json_serializable.dart copied to clipboard

Can't custom JsonConverter with constructor arguments. Error "Generators with constructor arguments are not supported"

Open phuongvt opened this issue 2 years ago • 9 comments
trafficstars

When I write DateTimeConverter extends from JsonConverter with constructor arguments. Then use

  @JsonKey(name: 'time')
  @DateTimeConverter(pattern: 'YYYY/MM/dd')
  final DateTime time;

run build_runner build print error "Generators with constructor arguments are not supported"

phuongvt avatar Nov 18 '23 02:11 phuongvt

@phuongvt Thanks for this awesome PR. When can we expect this into release?

faisalansari0367 avatar Nov 27 '23 14:11 faisalansari0367

For now If anyone wants to use a same JsonConverter for two purpose You can use a named constructor. For example:

Screenshot 2023-11-27 at 8 26 52 PM

And you can it use it as: Screenshot 2023-11-27 at 8 27 03 PM

faisalansari0367 avatar Nov 27 '23 14:11 faisalansari0367

@faisalansari0367 : Thank you for your support!

First of all, sorry for the late reply. In my case, I need to define many parameters in JsonConverter structure, and the parameters have too many different values because they are of type String => there can be many "named constructors" that need to be created without rarely reused. For example:

pattern= 'YYYY/MM/dd'
pattern= 'YYYY/MM/dd HH:mm:ss'
pattern= 'YYYY/MM/dd HH:mm'
pattern= 'YYYY-MM-dd'
...

so I still find "Generators with constructor arguments" necessary. I need MR as soon as possible to support my projects

Thank you!

phuongvt avatar Jan 15 '24 23:01 phuongvt

Have you considered adding named constructors with the values pre-populated? That should work.

kevmoo avatar Jan 16 '24 18:01 kevmoo

@kevmoo yes, I was considering creating 'named constructors' that are often reused. However, I still think supporting 'Generators with constructor arguments' is necessary

phuongvt avatar Jan 16 '24 23:01 phuongvt

@kevmoo yes, I was considering creating 'named constructors' that are often reused. However, I still think supporting 'Generators with constructor arguments' is necessary

This will add non-trivial complexity to this package, sadly.

kevmoo avatar Jan 16 '24 23:01 kevmoo

@kevmoo What do you think if I create a new class ArgumentsJsonConverter. JsonConverter I will throw an exception "Use ArgumentsJsonConverter to support constructor arguments or define named constructors (#1373)" instead of "Generators with constructor arguments are not supported"

phuongvt avatar Jan 17 '24 01:01 phuongvt

i believe I have found a convenient enough workaround.

in your Converter:

  const DecimalIntConverter.tenths() : this(places: -1);
  const DecimalIntConverter({this.places = 0, this.base = 10});

in your type:

   @DecimalIntConverter.tenths() double someValue;

MoralCode avatar Mar 06 '24 22:03 MoralCode