Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter Redux SnackBar

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?

like image 741
Vikas Avatar asked Jan 02 '23 12:01

Vikas


1 Answers

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.

like image 182
aqwert Avatar answered Jan 13 '23 14:01

aqwert