Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Set state method not updating the value

I can’t get the _onPageChanged to work. I am using it on a PageView.builder onPageChanged: _onPageChanged,. Whenever I change manually the _currentPage to for e.g 1 then it’s all fine. What is the issue here?

class Onboarding extends StatefulWidget {
  const Onboarding({Key? key}) : super(key: key);

  @override
  State<Onboarding> createState() => _OnboardingState();

}
class _OnboardingState extends State<Onboarding> {
  @override
  Widget build(BuildContext context) {

  int _currentPage = 0;

  final PageController _pageController = PageController(
    initialPage: 0
  );

   @override
   void dispose() {
     super.dispose();
      _pageController.dispose();
    }

    @override
    void initState() {
      super.initState();
      _currentPage++;
    }

    void _onPageChanged(int index) {
      setState(() {
        _currentPage = index;
      });
    }

    return SafeArea(
     ...code

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Take this code out of the build method into State.

int _currentPage = 0;

final PageController _pageController = PageController(
    initialPage: 0
  );

   @override
   void dispose() {
     super.dispose();
      _pageController.dispose();
    }

    @override
    void initState() {
      super.initState();
      _currentPage++;
    }

    void _onPageChanged(int index) {
      setState(() {
        _currentPage = index;
      });
    }

like this:

    class Onboarding extends StatefulWidget {
      const Onboarding({Key? key}) : super(key: key);
    
      @override
      State<Onboarding> createState() => _OnboardingState();
    
    }
    class _OnboardingState extends State<Onboarding> {
     int _currentPage = 0;
    
     final PageController _pageController = PageController(
        initialPage: 0
     );
    
     @override
     void initState() {
        super.initState();
        _currentPage++;
     }
    
     void _onPageChanged(int index) {
      setState(() {
            _currentPage = index;
      });
     }
    
    @override
    Widget build(BuildContext context) {
    return SafeArea(
         ...code;
    }
  @override
  void dispose() {
     super.dispose();
     _pageController.dispose();
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading