如何在 Flutter Cubit 中使用 StreamSubscription

问题描述

我遇到了一个问题,即对 cubit 的流订阅不监听 cubit 的发射状态。这是我如何在代码中实现它们的示例。

这是我想听的肘部

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 {}

这是我要订阅的肘子,我想听的肘子。

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();
  }
}

之后,我像下面这样调用 ButtonPressCubit emitButtonOnepressed()

MaterialButton(
  child: Text('Buton 2'),onpressed: () {
    BlocProvider.of<ButtonPressCubit>(context)
      .emitButtonTwopressed();
    },),

但这行不通。如何修复它以获得肘的状态。

解决方法

如果你在开始之前没有注册那个widget的Cubit,你应该注册

这就像告诉 flutter 这个 Cubit 是针对这个页面的,并且有一些方法可以做到这一点

第一:如果您有多个 Bloc 或

 MultiBlocProvider(
      providers: [
        //other Blocs or Cubits
        BlocProvider<XCubit>(
          create: (BuildContext context) => XCubit(),child: XWidget(),),//other Blocs or Cubits
      ],child: MaterialApp(),....);

第二:如文档中

class _AppState extends State<App> {
  final UserRepository _userRepository = UserRepository();
  AuthenticationBloc _authenticationBloc;

  @override
  void initState() {
    super.initState();
    _authenticationBloc = AuthenticationBloc(userRepository: _userRepository);
    _authenticationBloc.dispatch(AppStarted());
  }

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      bloc: _authenticationBloc,child: MaterialApp(
        home: BlocBuilder(
          bloc: _authenticationBloc,builder: (BuildContext context,AuthenticationState state) {
            //here is your widget you want to run
            return Container();
          },);
  }

但请记住,您应该在启动/运行小部件之前执行此操作

通常我会像第一种方法一样在开始时定义所有 Blocs 和 Cubits。在任何其他小部件运行之前。

那是你应该关心的另一件事,但是如果你使用的是 Bloc 而不是 Cubit 是你实现了 Bloc

{Listener,Builder..}在您的小部件中,以便您可以看到更改

  BlocBuilder<AddNewStudentBloc,AddNewStudentState>(
          builder: (context,state) {
//here you do respond for the state like 
// if State is Error return ErrorWidget
// else if the state is Success return SuccessWidget
// and so on....
return Container(); },);