简体   繁体   English

使用 Flutter BLOC 监听事件而不是状态

[英]Listen to Events instead of States with Flutter BLOC

I am using the Flutter BLOC library ( https://pub.dev/packages/bloc ) I know there is a way to "listen to" BLOC states changes (with the listen() function)我正在使用 Flutter BLOC 库 ( https://pub.dev/packages/bloc ) 我知道有一种方法可以“监听”BLOC 状态变化(使用 listen() 函数)

chatBloc.listen((chatState) async {
      if (chatState is ChatStateInitialized) {
        // do something
      }
    });

But is there a way to listen to BLOC events instead ?但是有没有办法监听 BLOC 事件呢? Just like I would do with a classical StreamController ?就像我对经典 StreamController 所做的那样? Thanks to all who will be willing to help :-)感谢所有愿意提供帮助的人:-)

Julien于连

Yes, you can listen to BLoC events by below code:是的,您可以通过以下代码收听 BLoC 事件:

BlocSupervisor.delegate = MyBlocDelegate();

And your main.dart similar to below code:你的main.dart类似于下面的代码:

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  BlocSupervisor.delegate = MyBlocDelegate();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: BlocProvider<CounterBLoC>(
        create: (ctx) => CounterBLoC(),
        child: TestBlocWidget(),
      ),
    );
  }
}

Here is your bloc_delegate.dart for listen to events of BLoC:这是您的bloc_delegate.dart用于侦听 BLoC 事件:

import 'package:bloc/bloc.dart';

class MyBlocDelegate extends BlocDelegate {
  @override
  void onEvent(Bloc bloc, Object event) {
    print(event);
    super.onEvent(bloc, event);
  }

  @override
  void onError(Bloc bloc, Object error, StackTrace stackTrace) {
    print(error);
    super.onError(bloc, error, stackTrace);
  }

  @override
  void onTransition(Bloc bloc, Transition transition) {
    print(transition);
    super.onTransition(bloc, transition);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM