2

I want to release everything when leaving the current screen.

Getx advising me to use onClose method of GetxController for this.

@override
void onClose() {
  pagingController.dispose();
  super.onClose();
}

He kept his promise, so nice. But it didn't take long! Let's dive in;

The controller has a future method called _fetchPage, it basically fetches page data and works with pagingController

If I leave the screen before completing the _fetchPage, the future remains working. Once the data is fetched, pagingController is accessed but it has been already disposed.

And finally, it prints Unhandled Exception: Exception: A PagingController was used after being disposed.

  Future<void> _fetchPage(int pageKey) async {
    try {
      var skip = pageKey == 0 ? 0 : (10 * pageKey);
      var data = await fetchDataOfPage(skip, limit);
      final isLastPage = data.length < limit;

      if (isLastPage) {
        pagingController.appendLastPage(data);
      } else {
        final nextPageKey = pageKey + 1;
        pagingController.appendPage(data, nextPageKey);
      }
    } catch (error) {
      pagingController.error = error;
    }
  }
blackkara
  • 4,900
  • 4
  • 28
  • 58
  • There are few things you have to take care: 1. make sure you have all the variables in controller. 2. you dont have to actually dispose the controller if the controller is bind with the route. So make sure you have bindings binded with the route using GetPage( name: _Paths.POST_DETAIL, page: () => FeedItemDetail(), binding: SocialFeedBinding(), ). so when the page is popped all the controller data will be deleted – Abhinav kumar sintoo Jul 18 '22 at 06:50
  • The pagingController is defined in the controller and bound with Binding. I can see the lifecycle logs of the Controller. But `infinite_scroll_pagination` docs emphasized using dispose method especially. – blackkara Jul 18 '22 at 10:05

1 Answers1

1

I had this exact problem and was able to fix it by checking that the widget is still mounted after retrieving the data:

  Future<void> _fetchPage(int pageKey) async {
    try {
      var skip = pageKey == 0 ? 0 : (10 * pageKey);
      var data = await fetchDataOfPage(skip, limit);

      // bail out if widget is no longer mounted
      if (!mounted) {
        return;
      }

      final isLastPage = data.length < limit;

      if (isLastPage) {
        pagingController.appendLastPage(data);
      } else {
        final nextPageKey = pageKey + 1;
        pagingController.appendPage(data, nextPageKey);
      }
    } catch (error) {
      pagingController.error = error;
    }
  }