Skip to content

BlocBuilder with Optional Build Condition #315

@felangel

Description

@felangel

Is your feature request related to a problem? Please describe.
Proposal to address #174

Describe the solution you'd like

Proposing to add an optional condition property to BlocBuilder which takes the previousState and currentState as arguments and must return a bool which determines whether or not to rebuild.

Usage

@override
Widget build(BuildContext context) {
  final TimerBloc _timerBloc = BlocProvider.of<TimerBloc>(context);
  return Scaffold(
    appBar: AppBar(title: Text('Flutter Timer')),
    body: Column(
      children: <Widget>[
        BlocBuilder(
          bloc: _timerBloc,
          builder: (context, state) => TimerText(duration: state.duration),
        ),
        BlocBuilder(
          condition: (prevState, currState) =>
              currState.runtimeType != prevState.runtimeType,
          bloc: _timerBloc,
          builder: (context, state) => Actions(),
        ),
      ],
    ),
  );
}
import 'package:equatable/equatable.dart';
import 'package:meta/meta.dart';

@immutable
abstract class TimerState extends Equatable {
  final int duration;

  TimerState(this.duration, [List props = const []])
      : super([duration]..addAll(props));
}

class Ready extends TimerState {
  Ready(int duration) : super(duration);
}

class Paused extends TimerState {
  Paused(int duration) : super(duration);
}

class Running extends TimerState {
  Running(int duration) : super(duration);
}

class Finished extends TimerState {
  Finished() : super(0);
}

In the above example, the Text widget with the remaining time will be rebuilt every time a new state is received (every second) whereas the Actions widget will only be rebuilt if the state runtimeType changes (Ready -> Running, Running -> Paused, etc...).

ezgif com-optimize

Describe alternatives you've considered
Lots of alternatives described in #174.

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions