How to use Flutter Bloc to state management

26 views Asked by At

I'm new to Flutter and learning about clean architecture, and I want to build a day-counting app. My app will store the first time users open the app and then retrieve this value for counting. It will get the initial date from the shared preferences and then calculate the number of days since that date. I'm using bloc as a state management tool, and this is my code.

class DayCountingBloc extends Bloc<DayCountingEvent, DayCountingState> {
  final RetrieveBeginDate _retrieveBeginDate;
  final StoreBeginDate _storeBeginDate;
  DayCountingBloc(
      RetrieveBeginDate retrieveBeginDate, StoreBeginDate storeBeginDate)
      : _retrieveBeginDate = retrieveBeginDate,
        _storeBeginDate = storeBeginDate,
        super(DayCountingInitial()) {
    on<DayCountingEvent>((event, emit) {
      emit(OnLoadingState());
    });
    on<RetrieveDateEvent>((event, emit) async {
      final res = await _retrieveBeginDate(NoParams());
      emit(OnRetrieveSuccessState(date: res));
    });
    on<StoreDateEvent>((event, emit) async {
      final res = await _storeBeginDate(event.date);
      if (res) {
        emit(OnStoreSuccessState());
      } else {
        emit(OnFailureState());
      }
    });
  }
}

And I want my app to update the time every second and display it on the user's screen. However, I don't know how I can calculate the time elapsed from the initial date to the current time every second using bloc.

0

There are 0 answers