I'm interested in recommendations for inheriting from a parent bloc. Say that I will be streaming animals.
class Animal {
final String color;
const Animal({this.color});
}
class Dog extends Animal {
final int tricksKnown;
const Dog({this.tricksKnown, String color}) : super(color: color);
}
class Bird extends Animal {
final int songsKnown;
const Bird({this.songsKnown, String color}) : super(color: color);
}
I would want a bloc, with events and states, that can set up Dog and Bird streams and react to events. The Flutter Bloc with Stream example shows that. But Dog and Bird would share the event UpdateColor as well as the machinery to listen to and close the stream, transformEvents using debounce, etc. Is there a way to structure the blocs so I could write methods for an AnimalBloc which could then be inherited by DogBloc and BirdBloc?
I have tried extending AnimalBloc, AnimalState, and AnimalEvent to DogBloc, DogState, and DogEvent, respectively, but Stream<DogState> mapEventToState(DogEvent event) is not a valid override of Stream<AnimalState> mapEventToState(AnimalEvent event). The best implementation I could come up with was creating AnimalBloc as a mixin with methods such as mapAnimalEventToState which could then be called by DogBloc and BirdBloc but it would be more elegant to simply call the parent implementation like this:
// in AnimalBloc
Stream<AnimalState> mapEventToState(AnimalEvent event) async* {
if (event is StartStream) {
subscription?.cancel();
subscription = zoo.stream(event.animal).listen((tick) => add(Tick(tick)));
}
}
// in DogBloc
Stream<DogState> mapEventToState(DogEvent event) async* {
super(event);
if (event is TeachTrick) {
yield Update(event.dog);
}
}
Any thoughts on the best way to do this?
Hi @mentoc3000 馃憢
Thanks for opening an issue!
I would love to setup a live code share session and work through your use-case together 馃憤
If you haven't already, can you please join the bloc discord server and send me a message? Thanks!
Hi @felangel. Thanks for being so willing to help me through this, but I believe I've figured it out. In the example I gave, mapEventToState should return an AnimalState rather than a DogState. That way DogBloc.mapEventToState can yield a DogState and in super.mapEventToState, AnimalBloc can yield an AnimalState.
Most helpful comment
Hi @felangel. Thanks for being so willing to help me through this, but I believe I've figured it out. In the example I gave,
mapEventToStateshould return anAnimalStaterather than aDogState. That wayDogBloc.mapEventToStatecan yield aDogStateand insuper.mapEventToState,AnimalBloccan yield anAnimalState.