Skip to content

Cache key collision in fromString for enums with same name from different packages #37

@jwgibanez

Description

@jwgibanez

We discovered an issue in enum_to_string v2.2.1 related to the recently added caching mechanism in the fromString method.


🐞 Problem

When two or more enums have the same name but come from different libraries or files, the internal caching mechanism causes a key collision, resulting in incorrect enum resolution.

This is because the cache key is currently generated as:

final enumType = T.toString();
final cacheKey = '$enumType:${camelCase.toString()}';

This approach does not account for the enum’s origin, meaning different enums with the same name (e.g., Status) will produce the same cache key (Status:false), causing incorrect behavior or cross-contamination between enum types.


🧪 Reproduction

// lib_a/status.dart
enum Status { active, inactive }

// lib_b/status.dart
enum Status { pending, failed }

When calling:

EnumToString.fromString(Status.values, 'active'); // from lib_a
EnumToString.fromString(Status.values, 'pending'); // from lib_b

Both calls will share the cache key "Status:false", leading to incorrect parsing or enum mismatches depending on call order.


🎯 Expected Behavior

The fromString method should create a unique cache key that distinguishes between enum types, even if they have the same name but come from different sources.


🛠️ Proposed Fix

Update the cache key generation to something more robust. Suggestions include:

✅ Option 1: Use runtimeType and hash

final enumType = enumValues.first.runtimeType.toString();
final enumHash = enumValues.first.runtimeType.hashCode;
final cacheKey = '$enumType:$enumHash:${camelCase.toString()}';

✅ Option 2: Use identityHashCode

final enumType = '${enumValues.first.runtimeType}::${identityHashCode(enumValues.first.runtimeType)}:${camelCase.toString()}';

This would ensure enums are correctly cached without collisions, even if they have the same name.


📌 Notes

  • This bug was introduced in version 2.2.1 as part of the performance improvement update.
  • Projects using multiple enums with identical names from different packages/modules are affected.
  • There is currently no way to disable or manually reset the cache (_enumStringCache) as a workaround.

🙏 Request

Please consider addressing this in a future patch release. I’d be happy to contribute a pull request if helpful.

Thanks for maintaining this helpful package!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions