FlutterBloc React To Blocs's Initial State
How can I make my bloc react to the bloc's initial state. In the example im trying to log something on the blocs initial state but nothing happens. It only prints the blocs constructor but not the print statement from facilityIntial
class FacilityBloc extends Bloc<FacilityEvent, FacilityState> {
FacilityBloc(this.facilityRepository)
: assert(facilityRepository != null),
super(FacilityInitial()) {
print('FacilitBlocConstructed');
}
final FacilityRepository facilityRepository;
@override
Stream<FacilityState> mapEventToState(
FacilityEvent event,
) async* {
print(event);
if (event is FacilityGetAll) {
yield* _mapGetAllFacilityToState(event);
} else if (event is FacilityInitial) {
print('Facility intial state');
}
}
Stream<FacilityState> _mapGetAllFacilityToState(FacilityGetAll event) async* {
yield FacilityLoading();
try {
List<Facility> facilities = await facilityRepository.loadAllFacility();
yield FacilityLoaded(facilities);
} on AppException catch (e) {
yield FacilityError(e.exceptionMessageId);
} catch (e) {
yield FacilityError(LocaleKeys.generalError);
}
}
}
Answer
If FacilityInitial
is a state, then it's a reason why you couldn't react to it in mapEventToState
function (in this function you can react only to events, not states). If mapEventToState
is an event (I can't say for sure, cause you haven't provided that info) it may conflict with the state class of the same name.
Also, you haven't provided the code where you creating your bloc instance. To be able to react to events (even on initial events) you are to add this event to bloc. It could look like this:
BlocProvider<FacilityBloc>(
lazy: false,
create: (context) => FacilityBloc(FacilityRepository())..add(FacilityInitialEvent()),
child: Text("My Text"),
)
In the example above I explicitly added FacilityInitialEvent
, so to the bloc be able to handle it. Also, I've changed the event name a bit, to avoid name conflict.
Related Questions
- → How do you create a 12 or 24 mnemonics code for multiple cryptocurrencies (ETH, BTC and so on..)
- → Flutter: input text field don't work properly in a simple example..... where am I wrong?
- → Can I customize the code formatting of Dart code in Atom?
- → Is it possible to develop iOS apps with Flutter on a Linux virtual machine?
- → Display SnackBar in Flutter
- → JSON ObjectMapper in Flutter
- → Material flutter app source code
- → TabBarSelection No such method error
- → How do I set the animation color of a LinearProgressIndicator?
- → Add different routes/screens to Flutter app
- → Is there a way to get the size of an existing widget?
- → How to share a file using flutter
- → Is there an easy way to find particular text built from RichText in a Flutter test?