[英]BlocBuilder's build method is not invoked when adding an event to this bloc from inside another bloc
I have bloc A
, created and provided above all the widgets of my app.我有
bloc A
,在我的应用程序的所有小部件之上创建和提供。
I have Bloc B
, created and provided in screen 1
.我有
Bloc B
,在screen 1
中创建和提供。
Bloc B
has a reference to Bloc A
and can add events to Bloc A
inside mapEventToState
of Bloc B
. Bloc B
具有对Bloc A
的引用,并且可以在Bloc B
的mapEventToState
Bloc A
添加事件。
Now the weird thing:现在奇怪的事情:
Inside screen 1, I have a BlocBuilder
of Bloc A
,在屏幕 1 内,我有一个
BlocBuilder
的Bloc A
,
If I add events directly ( blocAReference.add(blockAEvent)
the BlocBuilder
gets called when the state changes),如果我直接添加事件(
blocAReference.add(blockAEvent)
BlocBuilder
在 state 更改时被调用),
However when I add an event indirectly to Bloc A
( blocBrefrence.add(blockBEvent)
and then inside mapEventToState
of Bloc B
I add event to Bloc A
), then the BlocBuilder
is not invoked (but I can assure by print
ing to console that the event was added to Bloc A
)但是,当我将事件间接添加到
Bloc A
( blocBrefrence.add(blockBEvent)
,然后在Bloc B
的mapEventToState
中添加事件到Bloc A
)时,不会调用BlocBuilder
(但我可以通过print
向控制台保证事件已添加到Bloc A
)
I am using the flutter_bloc
library.我正在使用
flutter_bloc
库。
I figured out what was wrong.我发现出了什么问题。
The logic is all good except for one thing, I am using injectable
library to manage dependencies,逻辑都很好,除了一件事,我正在使用
injectable
库来管理依赖项,
and I was annotating my Bloc A
as @Injectable()
,我将我的
Bloc A
注释为@Injectable()
,
so when the library wants to inject Bloc A
into Bloc B
's constructor,因此,当库想要将
Bloc A
注入Bloc B
的构造函数时,
it was creating a new instance of Bloc A
every time and that instance was different from the one I was listening to in the BlocBuilder
(the one I am listening to is the one provided on top of the widget tree, I am looking it up using context.bloc<BlocA>()
)它每次都在创建一个
Bloc A
的新实例,并且该实例与我在BlocBuilder
中收听的实例不同(我正在收听的是在小部件树顶部提供的实例,我正在使用context.bloc<BlocA>()
)
So there are 2 solutions:所以有2个解决方案:
@Injectable()
annotation on Bloc A
but now I don't inject Bloc A
into Bloc B
but rather I send the instance of Bloc A
with every event added to Bloc B
(ie as a function parameter)Bloc A
上保留@Injectable()
注释,但现在我不将Bloc A
注入Bloc B
而是发送Bloc A
的实例,并将每个事件添加到Bloc B
(即作为 function 参数)@Injectable()
annotation from Bloc A
and replace it with @LazySingleton
so that all lookups using context.bloc<BlocA>()
will make injectable
library give me the same instance of the Bloc A
which I created above all my widgetsBloc A
中删除@Injectable()
注释并将其替换为@LazySingleton
以便所有使用context.bloc<BlocA>()
的查找将使injectable
库为我提供与我在所有小部件之上创建的Bloc A
相同的实例
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.