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

Som*_*oms 5 flutter bloc flutter-bloc

我正在使用 Flutter BLOC 库(https://pub.dev/packages/bloc)我知道有一种方法可以“监听”BLOC 状态更改(使用 Listen() 函数)

chatBloc.listen((chatState) async {
      if (chatState is ChatStateInitialized) {
        // do something
      }
    });
Run Code Online (Sandbox Code Playgroud)

但是有没有办法来监听 BLOC 事件呢?就像我对经典 StreamController 所做的那样?感谢所有愿意提供帮助的人:-)

朱利安

Tal*_*leb 3

是的,您可以通过以下代码监听 BLoC 事件:

BlocSupervisor.delegate = MyBlocDelegate();
Run Code Online (Sandbox Code Playgroud)

你的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(),
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

这是用于监听 BLoC 事件的bloc_delegate.dart :

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);
  }
}
Run Code Online (Sandbox Code Playgroud)