Skip to content

Simpler Build When Method #1521

Description

@ianjaspersantos

I think bloc builder is good when it comes to rebuilding widget. I just want to say that I feel it is a bit boilerplatey especially in the Generics part, buildWhen method and the builder method part. First, I just think that can we eliminate the bloc/cubit generic since I only wanted the state? Second, I think this "previousState.count != currentState.count" condition is the most common condition we can have in buildWhen that can be easily be replaceable with the propose feature below. For more complex condition I think its suitable to use BlocBuilder Widget.

class CounterText extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return BlocBuilder<CounterCubit, CounterState>(
      buildWhen: (previousState, currentState) => previousState.count != currentState.count,
      builder: (context, state) {
        final count = state.count;

        return Text(
          '$count',
          style: Theme.of(context).textTheme.headline4,
        );
      },
    );
  }
}

I think this easily manageable code when we have to many widgets with the same pattern unlike above? This should only rebuild when only the state.count changes and will not be affected by other state changes.

class CounterText extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final count = context.blocSelect((CounterState state) => state.count);

    return Text(
      '$count',
      style: Theme.of(context).textTheme.headline4,
    );
  }
}

Underlying Signature

extension BlocSelectContext on BuildContext {
      R blocSelect<T, R>(R selector(T value)) {}
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

enhancement candidateCandidate for enhancement but additional research is neededpkg:flutter_blocThis issue is related to the flutter_bloc package

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions