BlocSelector 用法

BlocSelector usage

在bloc 7.2.0中,BlocSelector有什么用?我需要这个小部件的实际示例。

BlocSelector<BlocA, BlocAState, SelectedState>(
  selector: (state) {
    // return selected state based on the provided state.
  },
  builder: (context, state) {
    // return widget here based on the selected state.
  },
)

答案可以在文档中找到:

BlocSelector is a Flutter widget which is analogous to BlocBuilder but allows developers to filter updates by selecting a new value based on the current bloc state. Unnecessary builds are prevented if the selected value does not change. The selected value must be immutable in order for BlocSelector to accurately determine whether builder should be called again.

BlocSelector 是默认 BlocBuilder 的优化版本。当状态发生变化时,BlocBuilder 总是会触发您的 UI 的更新。但是,使用 BlocSelector 您可以优化它并仅在您的状态的特定 field/property 发生变化时触发 UI 重建。这意味着,尽管如果您选择的 属性 保持不变,状态会有所不同,但 UI 不会被重建。