flutterEnumsToString icon indicating copy to clipboard operation
flutterEnumsToString copied to clipboard

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

Open jwgibanez opened this issue 4 months ago β€’ 0 comments

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!

jwgibanez avatar Jul 24 '25 11:07 jwgibanez