Skip to content

fix: dart_mappable default enum value#451

Merged
Carapacik merged 1 commit into
Carapacik:mainfrom
RootSoft:fix/unknown-enum-fallback
Apr 21, 2026
Merged

fix: dart_mappable default enum value#451
Carapacik merged 1 commit into
Carapacik:mainfrom
RootSoft:fix/unknown-enum-fallback

Conversation

@RootSoft
Copy link
Copy Markdown
Contributor

@RootSoft RootSoft commented Apr 8, 2026

This PR fixes enum generation for dart_mappable when unknown_enum_value: true is enabled.

Problem

Generated enums were emitting: @MappableEnum(defaultValue: 'unknown').

However, dart_mappable expects the actual enum case, not the serialized string value. Because of this, the generated mapper could not resolve the fallback enum index and still generated a throwing decode path for unknown backend values.

This caused older clients to crash when the backend introduced a new enum value.

Fix
The generator now emits the proper enum case reference instead of the encoded string value:

@MappableEnum(defaultValue: AnnouncementType.unknown)

This restores the expected dart_mappable behavior where unknown enum values safely fall back to the generated unknown enum case instead of throwing MapperException.unknownEnumValue(value).

Current behavior

It looks like @MappableEnum(defaultValue: ...) does not fallback when decoding an unknown enum value, and instead still throws MapperException.unknownEnumValue(...).

Example

This enum:

import 'package:dart_mappable/dart_mappable.dart';

part 'test.mapper.dart';

@MappableEnum(defaultValue: 'unknown')
enum Test {
  @MappableValue('info')
  info,

  @MappableValue('feature')
  feature,

  @MappableValue('unknown')
  unknown,
}

generates

@override
Test decode(dynamic value) {
  switch (value) {
    case 'info':
      return Test.info;
    case 'feature':
      return Test.feature;
    case 'unknown':
      return Test.unknown;
    default:
      throw MapperException.unknownEnumValue(value);
  }
}

Problem

If the backend later returns a new enum value, for example: { "type": "education" } decoding fails with: MapperException.unknownEnumValue(value) instead of falling back to: Test.unknown.

Expected behavior

When defaultValue is set, I would expect unknown enum values to decode to that default value, e.g.:

default:
  return Test.unknown;

This is especially important for API clients, where backend enums may evolve over time and older app versions should remain backward-compatible instead of crashing on new enum values.

@Carapacik Carapacik merged commit fb8bcec into Carapacik:main Apr 21, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants