flutter_bloc 4.0.0如何获取事件属性/参数

时间:2020-04-23 13:04:29

标签: flutter bloc flutter-bloc

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

我已经看到许多使用此库创建的示例,这些人通过event.paramter获取参数

就我而言,它不起作用。

问:问。如何在扩展相等时获得事件属性?内部集团。

events.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];
}

Bloc.dart

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();
      }
    }
  }
}

2 个答案:

答案 0 :(得分: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];
}

答案 1 :(得分: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]);

}