Flutter Bloc Library

Issue

In an application I am trying to implement the cart functionality. ItemDetailsScreen has addItemBtn, which returns null after the item is added. This function works fine, but the problem is that when I go to cartScreen and clear the cart, and then go back to ItemDetailsScreen, addItemBtn still returns null. To return the add state, I must use a hot reload. It looks like the state is not updating !? So how to solve this?

addItemBtn:

   BlocBuilder<CartFunctionsCubit, CartFunctionsState>(
      builder: (context, state) {
        return state.map(
          initial: (_) => Container(),
          cartLoaded: (state) => FlatButton(
            onPressed: state.userCart.items.contains(item)
                ? null
                : () {
                    context.read<CartFunctionsCubit>().addToCart(item);
                    context.read<CartFunctionsCubit>().startApp();
                  },
            child: state.userCart.items.contains(item)
                ? Text('Added')
                : Text('Add'),
          ),
        );
      },
    );

Cubit:

 Future<void> startApp() async {
    final userCart = await cartFacade.getUserCart();

    emit(CartFunctionsState.cartLoaded(userCart: userCart));
  }

  Future<void> addToCart(Item item) async {
    cartFacade.addToCart(item);
  }

Navigate to cart screen I am using

 Navigator.of(context).pushNamed('/cart');

Solution

you can await push function and then call the context.read<CartFunctionsCubit>().startApp();

await Navigator.of(context).pushNamed('/cart');
 context.read<CartFunctionsCubit>().startApp();

It will refresh the data when you came back from cart page

And if you want change the data when you change something in cart page. give boolean in Navigator.pop()

In Cart Page

 bool needToRefresh = false/// when there is a change set needToRefresh = true
    Navigator.pop(context,needToRefresh );/// and pass the value here

In Item Details Screen

bool needToRefresh = await Navigator.of(context).pushNamed('/cart');
if(needToRefresh !=null && needToRefresh)
   context.read<CartFunctionsCubit>().startApp();

It will refresh the data only when needToRefresh is true;

Answered By – SoloWolf93

Answer Checked By – Pedro (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *