【发布时间】:2021-12-09 08:16:18
【问题描述】:
我是这个状态管理领域的新手。所以我试图按照本教程(How to Save Products in a Wishlist using the BloC Pattern - EP10 - The eCommerce Series)进行操作,但 mapEventToState 已被弃用,所以我不知道该怎么做。
这是我的状态:
part of 'wishlist_bloc.dart';
abstract class WishlistState extends Equatable {
const WishlistState();
@override
List<Object> get props => [];
}
class WishlistLoading extends WishlistState {}
class WishlistLoaded extends WishlistState {
final WishlistModel wishlist;
const WishlistLoaded({this.wishlist = const WishlistModel()});
@override
List<Object> get props => [wishlist];
}
class WishlistError extends WishlistState {}
这是我的活动:
part of 'wishlist_bloc.dart';
abstract class WishlistEvent extends Equatable {
const WishlistEvent();
@override
List<Object> get props => [];
}
class StartWishlist extends WishlistEvent {}
class AddWishlistProduct extends WishlistEvent {
final ProductModel product;
const AddWishlistProduct(this.product);
@override
List<Object> get props => [product];
}
class RemoveWishlistProduct extends WishlistEvent {
final ProductModel product;
const RemoveWishlistProduct(this.product);
@override
List<Object> get props => [product];
}
这是我的集团:
import '../models/product_model.dart';
import '../models/wishlist_model.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:equatable/equatable.dart';
part 'wishlist_event.dart';
part 'wishlist_state.dart';
class WishlistBloc extends Bloc<WishlistEvent, WishlistState> {
WishlistBloc() : super(WishlistLoading()) {
on<StartWishlist>(_mapStartWishlistToState);
on<AddWishlistProduct>(_mapAddWishlistToState);
on<RemoveWishlistProduct>(_mapRemoveWishlistToState);
}
void _mapStartWishlistToState(event, emit) async {
emit(WishlistLoading());
try {
await Future.delayed(Duration(seconds: 1));
emit(WishlistLoaded());
} catch (_) {}
}
// Error ...
void _mapAddWishlistToState(event, emit) async {
if (state is WishlistLoaded) {
try {
emit(WishlistLoaded(
wishlist: WishlistModel(
products: List.from(state.wishlist.products)
..add(event.product))));
} catch (_) {}
}
}
void _mapRemoveWishlistToState(event, emit) async {}
}
但是我得到了这个错误:“没有为类型 'WishlistState' 定义 getter 'wishlist'。尝试导入定义 'wishlist' 的库,将名称更正为现有 getter 的名称,或定义getter 或字段名称 'wishlist'"。
如何在新版本的flutter_bloc中访问'wishlist'?谢谢。
【问题讨论】:
-
我明白了!您唯一需要做的就是转换状态。 (状态为 WishlistLoaded).wishlist.products
标签: flutter dart bloc state-management flutter-bloc