Skip to main content

avoid-passing-bloc-to-bloc

added in: 1.2.0
Free+

Warns when a Bloc depends on another Bloc.

Because blocs expose streams, it may be tempting to make a bloc which listens to another bloc. You should not do this. A bloc should only receive information through events and from injected repositories (i.e., repositories given to the bloc in its constructor).

If you're in a situation where a bloc needs to respond to another bloc, you can push the problem up a layer (into the presentation layer), or down a layer (into the domain layer).

Example

❌ Bad:

class BadBloc extends Bloc<CounterEvent, int> {
final OtherBloc otherBloc;
late final StreamSubscription otherBlocSubscription;

// LINT: Avoid creating a dependency between two 'Blocs'.
BadBloc(this.otherBloc) : super(0) {
otherBlocSubscription = otherBloc.stream.listen((state) {
add(Change(1));
});
}


void onChange(Change<int> change) {
super.onChange(change);
...
}
}

class OtherBloc extends Bloc<CounterEvent, int> {
OtherBloc() : super(0);


void onChange(Change<int> change) {
super.onChange(change);
...
}
}

✅ Good:

class GoodBloc extends Bloc<CounterEvent, int> {
// You can pass the stream instead
GoodBloc() : super(0) { }


void onChange(Change<int> change) {
super.onChange(change);
...
}
}

Additional Resources