有几种方法可以实现这一点。
正如您猜对的那样,您当然可以将一些字段移动到不同的肘部。另一种选择是实现不同的子类并在运行时或运行时ProductState
检查类型。BlocBuilder
BlocConsumer
class ProductCubit extends Cubit<ProductState> {
ProductCubit()
: super(
const ProductInitial(
ProductInfo(
productsPriceChange: [],
purchaseCount: [],
productSaleCount: 0,
productCategoryCount: 0,
productCount: 0,
productUnitCount: 0,
),
),
);
Future<void> loadProductPurchaseCount() async {
emit(ProductPurchaseCountLoadInProgress(state.productInfo));
try {
// TODO load product purchase count
final productPurchaseCount = <dynamic>[];
emit(
ProductPurchaseCountLoadSuccess(
state.productInfo.copyWith(
purchaseCount: productPurchaseCount,
),
),
);
} catch (_) {
emit(
ProductPurchaseCountLoadSuccess(state.productInfo),
);
}
}
}
abstract class ProductState extends Equatable {
const ProductState(this.productInfo);
final ProductInfo productInfo;
@override
List<Object?> get props => [productInfo];
}
class ProductInitial extends ProductState {
const ProductInitial(ProductInfo productInfo) : super(productInfo);
}
class ProductPurchaseCountLoadInProgress extends ProductState {
const ProductPurchaseCountLoadInProgress(ProductInfo productInfo)
: super(productInfo);
}
class ProductPurchaseCountLoadFailure extends ProductState {
const ProductPurchaseCountLoadFailure(ProductInfo productInfo)
: super(productInfo);
}
class ProductPurchaseCountLoadSuccess extends ProductState {
const ProductPurchaseCountLoadSuccess(ProductInfo productInfo)
: super(productInfo);
}
最后但并非最不重要的一点是,有一个相对较新的 Widget BlocSelector
,它可以让您检查状态以确定是否应该构建子级。
BlocSelector<BlocA, BlocAState, SelectedState>(
selector: (state) {
// return selected state based on the provided state.
},
builder: (context, state) {
// return widget here based on the selected state.
},
)
查看文档:https ://pub.dev/packages/flutter_bloc