Boby
Boby

Reputation: 1202

State not changing (stuck on initial)

Recently i'm learning about bloc_pattern , so i follow this https://medium.com/flutter-community/implementing-bloc-pattern-for-parsing-json-from-api-5ac538d5179f .

Here is my script

My Bloc File

class HotProductBloc extends Bloc<HotProductEvent, HotProductState> {
  HotProductRepository repository;

  HotProductBloc({@required this.repository});

  @override
  HotProductState get initialState => InitialHotProductsState();

  @override
  Stream<HotProductState> mapEventToState(HotProductEvent event) async* {
    print(event);
    if (event is FetchHotProductEvent) {
      yield HotProductsLoading();
      try {
        List<HotProducts> dataHotProduct = await repository.getHotProduct();
        yield HotProductsLoaded(hotproduct: dataHotProduct);
      } catch (e) {
        yield HotProductsError(message: e.toString());
      }
    }
  }
}

Repository file

abstract class HotProductRepository {
  Future<List<HotProducts>> getHotProduct();
}

class HotProductImplement implements HotProductRepository {
  @override
  Future<List<HotProducts>> getHotProduct() async {
    print("running");
    final response = await http.post(Configuration.url + "api/getHotProducts",
        body: {"userId": "abcde"});
    if (response.statusCode == 200) {
      var data = json.decode(response.body);
      List<dynamic> responseData = jsonDecode(response.body);
      final List<HotProducts> hotProducts = [];
      responseData.forEach((singleUser) {
        hotProducts.add(HotProducts(
          productId: singleUser['productId'],
          isNew: singleUser['isNew'],
          productName: singleUser['productName'],
          isHot: singleUser['isHot'],
          productImage: singleUser['productImage'],
          categoryId: singleUser['categoryId'],
          productPrice: singleUser['productPrice'],
          productDescription: singleUser['productDescription'],
          isLiked: singleUser['isLiked'],
          image1: singleUser['image1'],
          image2: singleUser['image2'],
          image3: singleUser['image3'],
          productColorId: singleUser['productColorId'],
        ));
      });
      return hotProducts;
    } else {
      throw Exception();
    }
  }

Event file

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

class FetchHotProductEvent extends HotProductEvent {
  @override
  List<Object> get props => null;
}

State file

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

class InitialHotProductsState extends HotProductState {}

class HotProductsLoading extends HotProductState {}

class HotProductsLoaded extends HotProductState {
  final List<HotProducts> hotproduct;

  HotProductsLoaded({@required this.hotproduct})
      : assert(hotproduct != null),
        super([hotproduct]);
}

class HotProductsError extends HotProductState {
  String message;
  HotProductsError({@required this.message});
  @override
  // TODO: implement props
  List<Object> get props => [message];
}

and here is how i implement the bloc

BlocListener <HotProductBloc, HotProductState>(
              listener: (context, state) {
                if (state is HotProductsError) {
                  Scaffold.of(context).showSnackBar(
                    SnackBar(
                      content: Text(state.message),
                    ),
                  );
                }
              },
              child: Container(
                child: BlocBuilder<HotProductBloc, HotProductState>(
                  builder: (context, state) {
                    print("BLoc State "+ state.toString());
                    if (state is InitialHotProductsState) {
                      return Text("Siaaap");
                    } else if (state is HotProductsLoading) {
                      return Text("Loading");
                    } else if (state is HotProductsLoaded) {
                      return Text("DONE");
                    } else if (state is HotProductsError) {
                      return Text("ERROR");
                    }else{
                      return Text("Unknown error");
                    }
                  },
                ),
              ),
            ),

when i run my script above, i get this on my Log

I/flutter ( 390): BLoc State InitialHotProductsState I/flutter ( 390): BLoc State InitialHotProductsState

Upvotes: 0

Views: 375

Answers (1)

Aditya Nigam
Aditya Nigam

Reputation: 999

You need to fire an event to start any change of state. Try adding this to somewhere in your build() method:

BlocProvider.of<HotProductBloc>(context).add(FetchHotProductEvent());

Upvotes: 2

Related Questions