Skip to content

Parameterized JsonConverter #1536

Closed as not planned
Closed as not planned

Description

@YukiAttano

I would like to request that JsonConverter classes support parameter.

Given this Example:

class UserProfile {

  @DateTimeLocalJsonConverter()
  final DateTime? birthdate;

  const UserProfile(this.birthdate);
} 
class DateTimeUtcJsonConverter extends JsonConverter<DateTime, String> {
  /// if true, utc to local conversion is disabled
  final bool disableFromUtc;

  /// if true, local to utc conversion is disabled
  final bool disableToUtc;

  const DateTimeUtcJsonConverter({this.disableFromUtc = false, this.disableToUtc = false});

  @override
  DateTime fromJson(String json) {
    if (disableFromUtc) return DateTime.parse(json);

    return DateTime.parse(json).toLocal();
  }

  @override
  String toJson(DateTime object) {
    if (disableToUtc) return object.toIso8601String();

    return object.toUtc().toIso8601String();
  }
}

As we see in the example, it was a bad idea to convert the birthday of a user into a utc date.
If the code generator would support parameter in JsonConverter, this would be helpful in reversing this mistake.

The alternative for parameter are currently writing a complete converter with the correct conversion or using a typedef.

const localDateTimeConverter = DateTimeUtcJsonConverter(disableToUtc: true);

Activity

  1. kevmoo commented on Oct 15, 2026

    @kevmoo
    Collaborator

    Closing as a duplicate of #1373 (tracked in PR #1539).

    In the meantime, you can work around this by defining a top-level const instance (const myConverter = MyConverter('arg');) and annotating the field with @myConverter.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions