Samuel
Samuel

Reputation: 592

How to implement infinite scroll pagination the right way

I am making a search request but the data returned comes with a pagination type. I have in my onchanged function in my TextField so that whenever I type something, it makes a get request. The first letter I type works fine but when I type again, nothing happens.

This is what I have in my onChanged function

onChanged: (value) {
      _pagingController.addPageRequestListener(
      (pageKey) {
      _fetchPage(pageKey, val.trim());
    },
   );
 },

Below is my _fetchPageFunction

Future<void> _fetchPage(int pageKey, String searchParam) async {
    final results = await searchRepo.getCareers(
          isSearching: true,
          searchParam: searchParam,
          token: token,
          page: pageKey,
        );
      hasNextPage = results['hasNextPage'];
      newItems.clear();
      newItems = results['schools'];
      print(newItems.length);
      if (!hasNextPage) {
        _pagingController.appendLastPage(newItems);
      } else {
        final nextPageKey = pageKey + 1;
        _pagingController.appendPage(newItems, nextPageKey);
      }
    } catch (error) {
      _pagingController.error = error.toString();
    }
  }

Below is my UI

PagedListView<int, dynamic>(
                  shrinkWrap: true,
                  pagingController: _pagingController,
                  builderDelegate: PagedChildBuilderDelegate<dynamic(
                    itemBuilder: (context, item, index) {
                      return ListTile(
                        leading: InitialsAvatar(name: item.name),
                        title: Text(
                          item.name ?? 'n/a',
                          style: theme.textTheme.bodyText1,
                        ),
                        subtitle: Text(
                          item.category,
                          style: theme.textTheme.labelMedium,
                        ),
                      );
                    },
                  ),
                ),

I tried removing the pageRequestLister after the _fetchPage funtion but it did not work. Is there any way I can do this? If this is not possible, is there any other package that can work for me?

Upvotes: 0

Views: 1368

Answers (1)

rrttrr
rrttrr

Reputation: 1846

Try adding _pagingController.refresh(); inside your onChanged().

onChanged: (value) {
      _pagingController.refresh();
      _pagingController.addPageRequestListener(
      (pageKey) {
      _fetchPage(pageKey, val.trim());
    },
   );
 },

Upvotes: 1

Related Questions