Dart增强枚举作为映射键-不能修改不可修改的映射



我正在从这个enum扩展迁移:

enum VgnItmTypeEnum {
@JsonValue(0)
nullObject,
@JsonValue(1)
groceryItm
}
extension VgnItmType on VgnItmTypeEnum {
static Map<VgnItmTypeEnum, Option> items = <VgnItmTypeEnum, Option>{
VgnItmTypeEnum.groceryItm: Option(
name: 'Grocery Item',
id: VgnItmTypeEnum.groceryItm.index,
iconCodePoint: 0xf291),
VgnItmTypeEnum.nullObject: Option(
name: '', id: VgnItmTypeEnum.nullObject.index, iconCodePoint: 0xf07a)
};
String get name => items[this]!.name;
int get id => items[this]!.id;
int get iconCodePoint => items[this]!.iconCodePoint;
Option get option => items[this]!;
}

这种增强enum:

enum VgnItmType {
nullObject(value: Option(name: 'Null Object', iconCodePoint: 0xf07a, id: 0)),
groceryItm(value: Option(name: 'Grocery Item', iconCodePoint: 0xf291, id: 1)),
);
const VgnItmType({required this.value});
final Option value;
static Map<VgnItmType, Option> items = <VgnItmType, Option>{
VgnItmType.groceryItm: Option(
name: 'Grocery Item',
id: VgnItmType.groceryItm.index,
iconCodePoint: 0xf291)
VgnItmType.nullObject:
Option(name: '', id: VgnItmType.nullObject.index, iconCodePoint: 0xf07a)
};
String get name => items[this]!.name;
int get id => items[this]!.id;
int get iconCodePoint => items[this]!.iconCodePoint;
Option get option => items[this]!;
}

我使用VgnItmTypeEnum作为Map键。现在,我已经升级到使用VgnItmType增强enum作为我的地图键,我得到一个错误,这段代码更新了一个给定的地图键(vgnItms)的map值:

@freezed
class VgnItmCache extends Entity
with LocalSaveMixin<VgnItmCache>, _$VgnItmCache {
const factory VgnItmCache(
{Map<VgnItmType, VgnItmEst>? vgnItms,
@Default(<S3ImageCommand>[]) List<S3ImageCommand> s3ImageCommands,
Option? vgnItmType,
FormType? formType,
@JsonKey(ignore: true) Ref? provider}) = _VgnItmCache;
// Here
void setVgnItm({required VgnItm vgnItm, VgnItmType? type}) {
final theType = type ?? myVgnItmType;
vgnItms![theType] = vgnItms![theType]!.copyWith(vgnItm: vgnItm);
}

错误:

不支持的操作,不能修改不可修改的映射。

以下是我如何构建VgnItmCache.vgnItms(请注意,VgnItmType.items在问题顶部的enum上):
@override
VgnItmCache $localFetch() {
var cache = VgnItmCache.fromJson(Map<String, dynamic>.from(
localDataSource.$localFetch<String>(keyToRead: ADD_VEGAN_ITEM)));
final populatedVgnItms = VgnItmType.items.map((k, v) { 
return MapEntry(k, cache.vgnItms?[k] ?? VgnItmEst.empty(k));
});
cache = cache.copyWith(vgnItms: populatedVgnItms);
return cache;
}

实际上是由于frozen从1升级到2造成的。使用@Freezed(makeCollectionsUnmodifiable: false)修复了这个问题。我已经升级了一些东西,以防它们对增强的枚举是必要的(json_seriablizable确实需要升级到至少6.1.5)。

最新更新