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 abuilder
and alistener
:builder
attribute is the widget builder callback you already knowlistener
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
andlistenWhen
, which trigger respectively thebuilder
orlistener
callbacks if they returntrue
.For example you can see how I've used
BlocConsumer
to show aSnackBar
when an error state occurs here.Don't mind the double check on the type
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).