JonasLevin
JonasLevin

Reputation: 2099

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.

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

      _pageController.animateToPage(_currentPage,
          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.

Upvotes: 1

Views: 3302

Answers (1)

Dr Younss AIT MOU
Dr Younss AIT MOU

Reputation: 1117

try this:

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

Upvotes: 1

Related Questions