Skip to content

Parameterized JsonConverter #1536

@YukiAttano

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);

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