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

时间:2020-01-11 21:51:11

标签: flutter bloc flutter-bloc

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

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

但是有办法代替监听BLOC事件吗?就像我会使用经典的StreamController吗? 感谢所有愿意提供帮助的人:-)

朱利安

1 个答案:

答案 0 :(得分:1)

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

BlocSupervisor.delegate = MyBlocDelegate();

和您的 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(),
      ),
    );
  }
}

这是您的 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);
  }
}