schultek / dart_mappable

Improved json serialization and data classes with full support for generics, inheritance, customization and more.
https://pub.dev/packages/dart_mappable
MIT License
165 stars 23 forks source link

[Proposal] Add the ability to change DateTimeEncoding mode for specific model #225

Closed AhmedLSayed9 closed 3 months ago

AhmedLSayed9 commented 3 months ago

I want the app to use the default DateTimeEncoding.utcIso8601String for all models.

But, for a specific model I need to use a different encoding mode (I want to send the date in local time zone not UTC for that model).

AhmedLSayed9 commented 3 months ago

Nvm, the default behavior can be overridden by including a custom mapper, i.e:

@MappableClass(
  includeCustomMappers: [_DateTimeMapper()],
)
//Model class

class _DateTimeMapper extends DateTimeMapper {
  const _DateTimeMapper();

  @override
  Object encode(DateTime self) {
    return self.toIso8601String();
  }
}
AhmedLSayed9 commented 2 months ago

As described in #231, using custom mapper will override the global behavior for all other classes.

The proper solution is to use MappingHook on the field and override afterEncode:

class _DateTimeHook extends MappingHook {
  const _DateTimeHook();

  @override
  Object? afterEncode(Object? value) {
    if (value is String) {
      return DateTime.parse(value).toLocal().toIso8601String();
    }
    return value;
  }
}