0

我对这个库和 BLOC 模式也很陌生,我需要基于特定 id 获取所有产品和单个产品。

我见过很多使用这个库创建的例子,那些人通过 event.paramter 获取参数

就我而言,它不起作用。

Q. 如何在扩展 equatable 时获取事件属性?集团内部。

事件.dart

abstract class ProductsEvent extends Equatable {
  const ProductsEvent();
}
class FetchProducts extends Equatable{
  @override
  List<Object> get props => [];

}

class FetchSingleProduct extends Equatable{
  final int id;
 const FetchSingleProduct({@required this.id}) : assert(id !=null);
  @override
  List<Object> get props => [id];
}

块飞镖

class ProductsBloc extends Bloc<ProductsEvent, ProductsState> {
  final AbstractProductsRepository abstractProductsRepository;
  ProductsBloc(this.abstractProductsRepository);

  @override
  ProductsState get initialState => InitialProductsState();

  @override
  Stream<ProductsState> mapEventToState(
    ProductsEvent event,

  ) async* {
    yield ProductsLoadingState();
    if(event is FetchProducts){
      try{

        final productsData = await abstractProductsRepository.fetchProducts();
        yield ProductsLoadedState(productsData);
      }on Error{
        print("Error in Block");
        yield ProductErrorState();
      }
    }else if(event is FetchSingleProduct){
      try{

        //Event.id  - not working.
        final productData = await abstractProductsRepository.fetchSingleProduct(**event.id**);
        yield SingleProductLoaded(productData);
      }on Error{
        print("Error in Block");
        yield ProductErrorState();
      }
    }
  }
}
4

2 回答 2

0

您需要如下扩展 ProductsEvent 并且您必须将道具传递给超类。

@immutable
abstract class ProductsEvent extends Equatable {
  ProductsEvent([List props = const []]) : super(props);
}

class FetchProducts extends ProductsEvent {
  @override
  String toString() => 'LoadTodos';
}

class FetchSingleProduct extends ProductsEvent {
  final int id;
  AddTodo(this.id) : super([id]);

}
于 2020-04-23T13:35:48.693 回答
0

你应该扩展 ProductsEvent

abstract class ProductsEvent extends Equatable {
  const ProductsEvent();
}

class FetchProducts extends ProductsEvent {
  @override
  List<Object> get props => [];
}

class FetchSingleProduct extends ProductsEvent {
  final int id;

  const FetchSingleProduct({@required this.id}) : assert(id !=null);

  @override
  List<Object> get props => [id];
}
于 2020-04-23T13:27:57.700 回答