I am with a problem that the stream subscription to a cubit doesn't listen to the emitting state of the cubit. Here's an example of how I implemented them in my code.
This is the cubit which I want to listen
class ButtonPressCubit extends Cubit<ButtonState> {
ButtonPressCubit() : super(ButtonNotPressed());
void emitButtonOnePressed() => emit(ButtonOnePressed());
void emitButtonTwoPressed() => emit(ButtonTwoPressed());
}
part of 'internet_cubit.dart';
@immutable
abstract class ButtonState {}
class ButtonNotPressed extends ButtonState {}
class ButtonOnePressed extends ButtonState {}
class ButtonTwoPressed extends ButtonState {}
This is the cubit that I want to subscribe to the cubit that I want to listen to.
class CounterCubit extends Cubit<CounterState> {
final ButtonPressCubit buttonPressCubit;
StreamSubscription buttonPressStreamSubscription;
CounterCubit({@required this.internetCubit})
: super(CounterState(counterValue: 0, wasIncremented: false)) {
buttonPressStreamSubscription = buttonPressCubit.listen(print);
}
void increment() => emit(
CounterState(counterValue: state.counterValue + 1, wasIncremented: true));
void decrement() => emit(CounterState(
counterValue: state.counterValue - 1, wasIncremented: false));
@override
Future<void> close() {
buttonPressStreamSubscription.cancel();
return super.close();
}
}
After that, I called the ButtonPressCubit emitButtonOnePressed() like below.
MaterialButton(
child: Text('Buton 2'),
onPressed: () {
BlocProvider.of<ButtonPressCubit>(context)
.emitButtonTwoPressed();
},
),
But this doesn't work. how to fix it to get the state of the cubit.