I am using redux in my flutter code. I have a button which on press dispatches an action to call an async API (in my middleware). What I want to do is when the api call executes and gives back response, I want to show the snackbar stating it is successfully updated data or a error message. My issue is how to show the snackbar by dispatching an action to show it. Or is there a better way to do this in redux?
Disclaimer: This is not code written in an IDE and run.. it is just a way to describe a solution to your question. There may be mistakes.
Assuming you have the Redux store and using async for the API call.
Your page widget:
...
_onSubmit(Store<MyState> store) {
store.dispatch(new SubmitAction(onCompleted: _onCompleted, onError: _onError))
}
_onCompleted() {
Scaffold.of(context).showSnackBar(new SnackBar(
content: new Text("Item Completed")));
}
_onError(error) {
Scaffold.of(context).showSnackBar(new SnackBar(
content: new Text("Error Occurred")));
}
Your Redux middleware:
apiMiddleware(Store<MyState> store, action, NextDispatcher next) {
if(action is SubmitAction) {
yourAPICall()
.then((data) => action.onCompleted())
.catchError((e) => action.onError(error));
}
next(action);
}
MyAction class:
typedef void VoidCallback();
typedef void ErrorCallback(error);
class MyAction {
MyAction({this.onCompleted, this.onError})
VoidCallback onCompeleted;
ErrorCallback onError;
}
Some of this could be done with futures but this is simple enough.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With