Reputation: 209
So, I have a cubit with a function that POSTs some data. I have three states, DataLoading
, DataError
and DataLoaded
for my cubit.
When the user taps on a button, I call the function in the cubit. After that, I have a BlocListener to wait until the Cubit emits the DataLoaded
state. The issue is that the listener is reacting to the state changes.
Button(
text: 'Add',
onTap: () {
final data = _textController.text;
context.read<PostDataCubit>().post(data);
BlocListener<PostDataCubit, PostDataState>(
listener: (context, state) {
if (state is DataLoaded) {
// navigate to another route
} else if (state is DataError) {
// show error
}
},
);
}
),
I've tried using await
on the read()
call but that didn't work. How do I react to the state changes here? Thanks.
Upvotes: 1
Views: 2240
Reputation: 916
This BlocListener
isn't listening because you have added the listener inside a function instead of adding it in widget tree. Wrap your button inside BlocConsumer
widget and it will works fine. Have a look into below code.
BlocListener<PostDataCubit, PostDataState>(
listener: (context, state) {
if (state is DataLoaded) {
// navigate to another route
} else if (state is DataError) {
// show error
}
},
builder: (context, state) {
return Button(
text: 'Add',
onTap: () {
final data = _textController.text;
context.read<PostDataCubit>().post(data);
});
},
),
Upvotes: 2