我有这个工会:
@freezed
abstract class VeganItem extends VeganItemAbstraction with _$VeganItem {
@With(GroceryItemMixin)
const factory VeganItem.groceryItem(
{int? id,
String? name,
String? companyName,
String? description,
List<Option>? tags,
int? rating,
List<ImagePickerImage>? images}) = GroceryItem;..........
中还有 4 个其他亚型VeganItem
。
我有这个联合类型,其中包含VeganItem
:
@freezed
abstract class VeganItemEstablishment extends VeganItemEstablishmentAbstraction
with _$VeganItemEstablishment {
@With(GroceryItemEstablishmentMixin)
const factory VeganItemEstablishment.groceryItemEstablishment(
{int? id,
Establishment? establishment,
GroceryItem? veganItem,
double? price,}) = GroceryItemEstablishment;..............
当我GroceryItemEstablishment.veganItem
成为 typeVeganItem
时,我可以像这样使用 copywith:
mvipVm.entity =
mvipVm.entity!.copyWith.veganItem!(id: null, images: null);
但是当我使它成为 type 时GroceryItem
,我必须像这样使用 copywith:
mvipVm.entity = mvipVm.entity!.map(
groceryItemEstablishment: (value) => value.copyWith(
veganItem: mvipVm.entity!.veganItem!
.copyWith(id: null, images: null) as GroceryItem),
menuItemEstablishment: (value) => value.copyWith(
veganItem: mvipVm.entity!.veganItem!
.copyWith(id: null, images: null) as MenuItem),
restaurantItemEstablishment: (value) => value.copyWith(
veganItem: mvipVm.entity!.veganItem!
.copyWith(id: null, images: null) as RestaurantItem),
eventItemEstablishment: (value) => value.copyWith(
veganItem: mvipVm.entity!.veganItem!
.copyWith(id: null, images: null) as EventItem),
groceryStoreItemEstablishment: (value) => value.copyWith(
veganItem: mvipVm.entity!.veganItem!
.copyWith(id: null, images: null) as GroceryStoreItem),
);
文档提到该字段必须在所有子类型上才能在copyWith
. 但是如果有相同的字段但有不同的子类型呢?
是否有替代解决方案可以GroceryItemEstablishment.veganItem
让我在字段中输入子类型以提供更简洁的copyWith
语法?
编辑:到目前为止,另一种选择是保留veganItem
为超类型(VeganItem
),并GroceryItem
在必要时将其强制转换为子类型(),这样更易于管理。