Bloc: Improve DartDocs for buildWhen

Created on 2 Oct 2020  路  3Comments  路  Source: felangel/bloc

Describe the bug
I worry that people will use buildWhen and assume that it provides security about what state is passed to the builder.
I believe this is a misuse, as the builder will always receive the bloc's current state, when it is initially built, and that can be anything, in theory.
Another concern is that people are using buildWhen to filter out some states, which would mean that their UI is showing a stale state. We should instead model our states differently to contain the new data on states which are being built by the UI.

Current DartDocs

/// {@template bloc_builder_build_when}
/// An optional [buildWhen] can be implemented for more granular control over
/// how often [BlocBuilder] rebuilds.
/// [buildWhen] will be invoked on each [cubit] `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 previous `state` will be initialized to the `state` of the [cubit] when
/// the [BlocBuilder] is initialized.
/// [buildWhen] is optional and if omitted, it will default to `true`.
///
/// ```dart
/// BlocBuilder<BlocA, BlocAState>(
///   buildWhen: (previous, current) {
///     // return true/false to determine whether or not
///     // to rebuild the widget with state
///   },
///   builder: (context, state) {
///     // return widget here based on BlocA's state
///   }
///)
/// ```
/// {@endtemplate}

Additional context
We discussed this shortly in Discord, and I have also seen suggestions in discord to use buildWhen, to not rebuild when the bloc goes into an error state.

documentation enhancement flutter_bloc

Most helpful comment

@omidraha there is listenWhen on BlocListener 馃憤

All 3 comments

I propose that we add a line, that explains that this should be used only for optimisations.

/// {@template bloc_builder_build_when}
/// An optional [buildWhen] can be implemented for more granular control over
/// how often [BlocBuilder] rebuilds.
/// [buildWhen] should only be used for performance optimisations, as it provides no security about the state passed to the [builder] function.
/// [buildWhen] will be invoked on each [cubit] `state` change.
/// ...

Why there is no buildWhen for BlocListener same as BlocBuilder?
I know BlocListener only runs once for every type of state, but when we have many states with different types I think it's useful.

@omidraha there is listenWhen on BlocListener 馃憤

Was this page helpful?
0 / 5 - 0 ratings

Related issues

craiglabenz picture craiglabenz  路  3Comments

clicksocial picture clicksocial  路  3Comments

abinvp picture abinvp  路  3Comments

1AlexFix1 picture 1AlexFix1  路  3Comments

nerder picture nerder  路  3Comments