Search code examples
flutterdartbloccubit

how to access to emit state in the cubit


i have a cubit that emit a cart modal, everything works find but when I fetch the emited state from the cubit I can not, so what I am looking for is to access to emited data from the cubit and here is my modal

class CartModal {
  late int storeId;
  late String storeName;
  late String storeImg;
  List<CartProductListModal>? items;
  late String? finalPrice;

  CartModal(
      {required this.storeId,
      required this.storeName,
      required this.storeImg,
      this.items,
      this.finalPrice});
    }

and here is my state in cubit

class CartStartStoreState extends CartState {
  final CartModal item;
  CartStartStoreState({required this.item});
  @override
  List<Object?> get props => [item];
}

and here is my way of fetch the data of the emit state in cubit

if (state is CartStartStoreState) {
  print(state.props[0]);
}

the output is "Instance of 'CartModal'" but I need to access to the specific thing inside which is storeId for example


Solution

  • To access specific properties of the emitted CartModal object inside the CartStartStoreState, you can cast the state to CartStartStoreState and then access the properties directly. Here's how you can modify your code:

    if (state is CartStartStoreState) {
        CartModal cartModal = (state as CartStartStoreState).item;
        print('Store ID: ${cartModal.storeId}');
        print('Store Name: ${cartModal.storeName}');
        // Access other properties as needed
    }
    

    By casting state to CartStartStoreState, you can access the item property, which contains the CartModal object. Then, you can access specific properties of the CartModal object directly, such as storeId, storeName, etc.

    This way, you'll be able to access the specific properties inside the emitted CartModal object from the cubit state.