flutterEnumsToString
flutterEnumsToString copied to clipboard
Cache key collision in fromString for enums with same name from different packages
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.1as 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!