Flutter Redux SnackBar

2,257

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.

Share:
2,257
Vikas
Author by

Vikas

Updated on December 04, 2022

Comments

  • Vikas
    Vikas over 1 year

    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?

  • Vikas
    Vikas about 6 years
    Thanks a lot. This approached worked. The other way I found was to use a global key and in the middleware use this key to show the snackbar after getting response from the api.
  • aqwert
    aqwert about 6 years
    Sure.. whatever works and you are happy with the level of coupling the Middleware has with the UI
  • NikolaDjokic
    NikolaDjokic about 6 years
    What if, when submit is clicked I also send the loading action. This will trigger the current widget to be replaced with a new one, displaying a progress bar. The callbacks will be left pointing to a destroyed context. Are callbacks a safe mechanism for Stateless widgets?
  • aqwert
    aqwert about 6 years
    Depends on the context you are passing. If you are staying on the same page you can pass the pages context, not the button's.
  • Gurleen Sethi
    Gurleen Sethi almost 6 years
    But is this ok with the architecture that Redux proposes?
  • s.j
    s.j over 3 years
    @aqwert getting this error while showing snackbar in success call of api