Home > database >  Set state method not updating the value
Set state method not updating the value

Time:12-23

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

CodePudding user response:

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();
  }
  • Related