BlocSelector usage

Issue

In bloc 7.2.0, What is the usage of BlocSelector ? I need a practical example for this widget.

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.
  },
)

Solution

The answer could be found in the documentation:

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 is the optimised version of the default BlocBuilder. When the state changes, BlocBuilder always triggers an update of your UI. However, with BlocSelector you could optimise this and trigger the UI rebuild only when the specific field/property of your state changes. Meaning, despite that the state is different if your selected property remains the same, the UI won’t be rebuilt.

Answered By – mkobuolys

Answer Checked By – Pedro (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.