dart 有什么区别:BlocBuilder & buildWhen vs BlocSelector

sq1bmfud  于 2023-09-28  发布在  其他
关注(0)|答案(1)|浏览(114)

我在看评论文档

/// An optional [buildWhen] can be implemented for more granular control over
/// how often [BlocBuilder] rebuilds.
/// [buildWhen] should only be used for performance optimizations as it
/// provides no security about the state passed to the [builder] function.
/// [buildWhen] will be invoked on each [bloc] `state` change.
/// [buildWhen] takes the previous `state` and current `state` and must
/// return a [bool] which determines whether or not the [builder] function will
/// be invoked.

/// The [selector] function which will be invoked on each widget build
/// and is responsible for returning a selected value of type [T] based on
/// the current state.
final BlocWidgetSelector<S, T> selector;

在我看来,就像在buildWhen的情况下,检查将一直执行,而如果返回false,则不会进行重建。
Selector的情况下,它看起来像每次都会调用build方法,但如果选择器返回相同的结果,则状态将相同。
这与我在调试代码时看到的情况并不完全相同,因为只有当Selector状态发生变化时才会调用builder,就像buildWhen返回true时一样。
那么这两种方法的实际区别是什么呢?除了语法之外,还有其他的吗?

ffscu2ro

ffscu2ro1#

BlocSelectorBlocBuilder的目的都是返回一个只依赖于一小部分状态的Widget
BlocSelector允许通过基于当前块状态选择新值来过滤更新:

BlocSelector<LoginBloc, LoginState, String>(
  selector: (LoginState state) => state.username,
  builder: (context, String username) {
    // Build widget based on `username` of LoginState
    // This builder only call when state.username change
  },
);

BlocBuilder没有filter函数,只有condition函数来决定builder函数是否运行

BlocBuilder<LoginBloc, LoginState>(
  buildWhen: (previousState, state) => previousState.username != state.username,
  builder: (context, state) {
    final username = state.username;
    // This builder only call when state.username change
  },
);

它们有相同的目标,但我认为BlocSelector的目标比BlocBuilder更明确,而且它也节省了一些代码。

相关问题