0

How can I pass a bloc object to a widget as a parameter like this:

I want to be able to pass either one bloc (TimerBloc) or another bloc (AnotherBloc) into this class and use that to return the BlocBuilder with that bloc.

Like either this: TimerField(bloc: TimerBloc) or this: TimerField(bloc:AnotherBloc)

class TimerField extends StatelessWidget {
  final [Not sure of the class] bloc;

  const TimerField({
    Key key,
    @required this.bloc,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<[THE BLOC THAT WAS PASSED IN], [AND THE STATE]>(
      .......
Gerry
  • 1,159
  • 1
  • 14
  • 29

1 Answers1

0
abstract class BaseBloc extends Bloc<EventType, StateType> {}

class TimerBloc extends BaseBloc {
  @override
  StateType get initialState => // ...

  @override
  Stream<StateType> mapEventToState(EventType event) async* {
    // ...
  }
}

class AnotherBloc extends BaseBloc {
  @override
  StateType get initialState => // ...

  @override
  Stream<StateType> mapEventToState(EventType event) async* {
    // ...
  }
}
class TimerField extends StatelessWidget {
  final BaseBloc bloc;

  const TimerField({
    Key key,
    @required this.bloc,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<BaseBloc, StateType>(
      bloc: bloc,
      builder: ....
    );
  }
Federick Jonathan
  • 2,726
  • 2
  • 13
  • 26
  • Thanks, I just added that as my attempt to get it to work, see the thing is I want to be able to pass either one bloc (TImerBloc) or another bloc (AnotherBloc) into this class and use that to return the BlocBuilder with that bloc. Your answer would only work for a TimerBloc, hence why I was trying the Bloc bloc part of my code, to show that's what I needed, I'll update my question too. – Gerry Jun 20 '20 at 12:40