show alert on cubit state in flutter


I know we can return different widgets on certain state of cubit, but how can we show an alert or other interactions on states:

BlocBuilder<LoginCubit, LoginState> (
  builder: (context, LoginState loginState) {
    if (loginState is LoginInitial) {
      return Text("LoginInitial");
    } else if (loginState is LoginLoading) {
      return Text("LoginLoading");
    } else if (loginState is LoginLoaded) {
      return Text("LoginLoaded");
    } else if (loginState is LoginError) {
      return Text("LoginError");
    } else {
      return Container();

here in LoginError I want to show an alert dialog.


You can use BlocConsumer, which has both a builder and a listener:

  • The builder attribute is the widget builder callback you already know
  • The listener is a callback called when the state changes and you can do pretty much anything there.

For more fine grained control you can use buildWhen and listenWhen, which trigger respectively the builder or listener callbacks if they return true.

For example you can see how I’ve used BlocConsumer to show a SnackBar when an error state occurs here.

Don’t mind the double check on the type

if (state is RegionalReportLoadingError)

because it’s probably useless (according to the docs) and I just wanted to be sure about that when I did not have the usage of listenWhen very clear.

You can check more about BlocConsumer in the docs (Unfortunately I cannot link the anchor).

Answered By – magicleon94

Answer Checked By – David Marino (FlutterFixes Volunteer)

Leave a Reply

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