SinaMN75
SinaMN75

Reputation: 7659

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.

Upvotes: 0

Views: 2900

Answers (2)

lomza
lomza

Reputation: 9716

Showing dialogs, snackbars, exiting the screen or navigating somewhere else - these kind of tasks should be done in listeners, like this:

useCubitListener<BookDetailsCubit, BookDetailsPageState>(cubit, (cubit, state, context) {
  state.maybeWhen(
    saveBook: () => context.router.pop<bool>(true),
    deleteBook: () => context.router.pop<bool>(true),
    orElse: () => null,
  );
}, listenWhen: (state) => (state is BookDetailsPageSaveBook || state is BookDetailsPageDeleteBook));

Here I used cubits with hooks. useCubitListener() is a global function. More on this in my Flutter cubits + hooks tutorial.

Upvotes: 0

magicleon94
magicleon94

Reputation: 5182

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).

Upvotes: 3

Related Questions