gpt4 book ai didi

flutter - Flutter Bloc 依赖项的多个监听器 - 接收先前的状态

转载 作者:行者123 更新时间:2023-12-05 09:33:09 35 4
gpt4 key购买 nike

这是我的 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(),
)

关于flutter - Flutter Bloc 依赖项的多个监听器 - 接收先前的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67394213/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com