我在看评论文档
/// 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时一样。
那么这两种方法的实际区别是什么呢?除了语法之外,还有其他的吗?
1条答案
按热度按时间ffscu2ro1#
BlocSelector
和BlocBuilder
的目的都是返回一个只依赖于一小部分状态的WidgetBlocSelector
允许通过基于当前块状态选择新值来过滤更新:BlocBuilder
没有filter函数,只有condition函数来决定builder函数是否运行它们有相同的目标,但我认为BlocSelector的目标比BlocBuilder更明确,而且它也节省了一些代码。