Flutter Bloc access state inside of initState function


I have created the state currentPage for a carousel of images. My three possible events are increment/decrement and set page which will change the currently viewed page of the carousel. I’m using a timer to increment or reset the state after 5 seconds depending on what the currently viewed page is.

  void initState() {
    Timer.periodic(const Duration(seconds: 5), (Timer timer) {
      if (_currentPage < 2) {
      } else {
        context.read<CarouselBloc>().add(SetCurrentPage(newPage: 0));

          duration: const Duration(milliseconds: 300), curve: Curves.easeIn);

I now want to change the _currentPage variable to the state state.currentPage. But I don’t know how to access the state from within my void initState function. I’m wrapping my carousel widget with a BlocProvider to read the CarouselBloc from the context and emit the events depending on the current page.
I hope I can get some help regarding the access of the state.currentPage from within the initState function.


try this:

var page = context.read<CarouselBloc>().state.currentPage

Answered By – Younss AIT MOU

Answer Checked By – Mary Flores (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *