这是我的 Flutter 应用 MultiBlocProvider 设置;
MultiBlocProvider(
providers: [
BlocProvider<LocationBloc>(create: (BuildContext context) {
return LocationBloc();
}),
BlocProvider<AddressBloc>(create: (BuildContext context) {
return AddressBloc(
location: BlocProvider.of<LocationBloc>(context)
..add(LocationStarted()))
..add(AddressStarted());
}),
BlocProvider<CampaignBloc>(
create: (BuildContext context) => CampaignBloc(
addressBloc: BlocProvider.of<AddressBloc>(context),
repo: CampaignsRepository())
..add(CampaignsInitial()),
),
BlocProvider<BusinessBloc>(
create: (BuildContext context) => BusinessBloc(
addressBloc: BlocProvider.of<AddressBloc>(context),
repo: BusinessRepository())
..add(BusinessInitial()),
)
],
child: MaterialApp(...)
,
)
LocationBloc 从位置服务获取位置。 AddressBloc 从 LocationBloc 获取更新的位置并将其转换为地址。
CampaignBloc 在其构造函数中监听 AddressBloc 流以了解地址(位置)的变化,并针对已更改的位置发出事件。
CampaignBloc({required this.repo, required this.addressBloc})
: super(CampaignState()) {
_addressSubscription =
addressBloc.stream.asBroadcastStream().listen((AddressState state) {
if (state is AddressLoadSuccess) {
Location location = state.location;
add(CampaignChangedLocation(location: location));
}
});
}
BusinessBloc 在其构造函数中做同样的事情,并且(应该)为更改后的位置发出业务。
BusinessBloc({required this.repo, required this.addressBloc})
: super(BusinessInitial()) {
_addressSubscription =
addressBloc.stream.asBroadcastStream().listen((AddressState state) {
if (state is AddressLoadSuccess) {
Location location = state.location;
add(BusinessChangedLocation(location: location));
}
});
}
HomeView 有一个构建事件列表的 BlocBuilder
AlliesView 有一个 BlocBuilder
CampaignBloc 在构建 HomeView 时正在接收更新的位置,但在转换到 AlliesView 时,AddressBloc 流上的监听器没有接收到更新的位置,因为它在事件后订阅了流。如何在 AddressBloc 流的后续监听器中获取更新后的位置?
最佳答案
MultiBlocListener(
listeners: [
BlocListener<BlocA, BlocAState>(
listener: (context, state) {},
),
BlocListener<BlocB, BlocBState>(
listener: (context, state) {},
),
BlocListener<BlocC, BlocCState>(
listener: (context, state) {},
),
],
child: ChildA(),
)
https://stackoverflow.com/questions/67394213/