这是我的 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 流的后续侦听器中获取更新的位置?
答案 0 :(得分:0)
我想出了一个解决方案 - 使用 rxdart 的 ReplaySubject。所以在 AddressBloc 我用
覆盖#stream ReplaySubject<AddressState>? s;
@override
get stream {
if (s == null) {
s = new ReplaySubject<AddressState>();
Stream upstream = super.stream;
upstream.listen((value) {
s!.add(value);
});
}
return s!;
}
现在,当我创建订阅 AddressBloc 的 BusinessBloc 时,我会在 AddressBloc 流中获得以前的状态。
答案 1 :(得分:0)
MultiBlocListener(
listeners: [
BlocListener<BlocA, BlocAState>(
listener: (context, state) {},
),
BlocListener<BlocB, BlocBState>(
listener: (context, state) {},
),
BlocListener<BlocC, BlocCState>(
listener: (context, state) {},
),
],
child: ChildA(),
)