"dispose" function not working when the current tab is changed

145 Views Asked by At

Whenever I switch between tabs while using CupertinoTabScaffold, my dispose function is not being called.

class CustumPageViewBuilder extends StatefulWidget {
  const CustumPageViewBuilder({
    super.key,
    required this.words,
  });

  final List words;

  @override
  State<CustumPageViewBuilder> createState() => _CustumPageViewBuilderState();
}

class _CustumPageViewBuilderState extends State<CustumPageViewBuilder> {
  late final PageController ctrlPageView;
  late final timer;
  @override
  void initState() {
    super.initState();
    ctrlPageView = PageController(initialPage: 0);
    int currentIndex = 0;
    timer = Timer.periodic(
      const Duration(seconds: 2),
      (timer) {
        if(currentIndex==10){
          currentIndex=0;
        }

        ctrlPageView.animateToPage(
          currentIndex++,
          duration: const Duration(milliseconds: 800),
          curve: Curves.easeIn
        );
        
      }
    );
  }

  @override
  void dispose() { // not called

    timer.cancel();
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {
    return PageView.builder(
      
      controller: ctrlPageView,
      itemCount: widget.words.length,
      itemBuilder: (context, index) {
        return Column(
          
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
           
            Text(
              widget.words[index]["true"]!,
              style: const TextStyle(
                fontSize: 18
              ),
            ),
            
            const Center(
              child: Icon(
                CupertinoIcons.arrow_2_circlepath,
                color: CupertinoColors.systemPink,
                size: 30,
              ),
            ),

            
            
            Text(
              widget.words[index]["false"]!,
              style: const TextStyle(
                fontSize: 18
              ),
            ),
            
          ],
        );
      },
    );
  }
}

I have a timer that lets me switch pages every two seconds (The page changes with the controller of PageView.builder.) but "dispose" function not working when the current tab is changed. I am using CupertinoTabScaffold and CupertinoTabBar in my code.

0

There are 0 best solutions below