Flutter Bloc Library
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');
Answer
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;
Related Questions
- → How do you create a 12 or 24 mnemonics code for multiple cryptocurrencies (ETH, BTC and so on..)
- → Flutter: input text field don't work properly in a simple example..... where am I wrong?
- → Can I customize the code formatting of Dart code in Atom?
- → Is it possible to develop iOS apps with Flutter on a Linux virtual machine?
- → Display SnackBar in Flutter
- → JSON ObjectMapper in Flutter
- → Material flutter app source code
- → TabBarSelection No such method error
- → How do I set the animation color of a LinearProgressIndicator?
- → Add different routes/screens to Flutter app
- → Is there a way to get the size of an existing widget?
- → How to share a file using flutter
- → Is there an easy way to find particular text built from RichText in a Flutter test?