是的,您可以通过以下代码收听 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 事件的 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);
}
}