简体   繁体   English

即使没有状态更改,Flutter Bloc Listener 也在重建

[英]Flutter Bloc Listener rebuilding even though there is no state change

I have an App which uses a bottom navigation bar to switch between pages.我有一个应用程序,它使用底部导航栏在页面之间切换。 To do this, I'm using Bloc .为此,我正在使用Bloc On one of the tab pages, I render a list with some items in it.在其中一个标签页上,我呈现了一个列表,其中包含一些项目。 This list is built when the State changes to SchedulesLoaded(see picture).这个列表是在 State 更改为 SchedulesLoaded 时构建的(见图)。

The problem I have is that when I'm changing pages using the bottom navigation bar(Which is using a completely different Bloc) the list in the picture is being rebuilt.我遇到的问题是,当我使用底部导航栏(使用完全不同的 Bloc)更改页面时,正在重建图片中的列表。 The Listener is actually redrawing the widget without a change in the Bloc State it's listening to.侦听器实际上正在重绘小部件,而没有更改它正在侦听的 Bloc 状态。 I can't get my head around why it is happening.我无法理解为什么会发生这种情况。 Does anyone have a clue?有人有线索吗?

I found this link discussing the issue, but I got nothing useful out of it.我发现这个链接讨论了这个问题,但我没有从中得到任何有用的信息。

在此处输入图片说明

For anyone looking at this now, you can call buildWhen after building Builder to provide some condition when to build.对于现在正在查看此内容的任何人,您可以在构建 Builder 后调用 buildWhen 以提供何时构建的一些条件。

From docs:从文档:

An optional [buildWhen] can be implemented for more granular control over how often [BlocBuilder] rebuilds.可以实现可选的 [buildWhen] 以更精细地控制 [BlocBuilder] 重建的频率。 [buildWhen] will be invoked on each [cubit] state change. [buildWhen] 将在每次 [cubit] state更改时调用。 [buildWhen] takes the previous state and current state and must return a [bool] which determines whether or not the [builder] function will be invoked. [buildWhen] 获取之前的state和当前state并且必须返回一个 [bool] 来确定是否将调用 [builder] 函数。 The previous state will be initialized to the state of the [cubit] when the [BlocBuilder] is initialized.之前的state会在[BlocBuilder]初始化时被初始化为[cubit]的state [buildWhen] is optional and if omitted, it will default to true . [buildWhen] 是可选的,如果省略,它将默认为true

Example:例子:

    return Scaffold(
  appBar: AppBar(
    title: BlocBuilder<Bloc, State>(
      buildWhen: (p, c) => p.isEditing != c.isEditing,
      builder: (context, state) {
        return Text(state.isEditing ? 'Edit' : 'Create');
      },
    ),

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM