Home > Net >  The method 'dispose' & jumptopage can't be unconditionally invoked because the receiv
The method 'dispose' & jumptopage can't be unconditionally invoked because the receiv

Time:11-09

i try to use pageController in flutter but i found problem with unconditionally why "dispose" need to have value i have no idea with this please help me figured out

here is my code

PageController? pageController;
  int pageIndex = 0;

  void initState() {
    super.initState();
    pageController = PageController();
  }

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

  onPageChanged(int pageIndex) {
    setState(() {
      this.pageIndex = pageIndex;
    });
  }

  onTap(int pageIndex) {
    pageController.jumpToPage(pageIndex);
  }

enter image description here

enter image description here

CodePudding user response:

pageController.dispose();

At this point, since pageController is declared as PageController? pageController; the compiler cannot rule out that it might be null. You cannot call a method on null and since the compiler cannot rule it out, it won't let you.

You can do something like this:

final temp = pageController;
if(temp != null) {
  temp.dispose();
}

or if you want to use the power of Dart and have that done for you under the hood:

pageController?.dispose();
  • Related