(index out of range )i use a method for pagination to show 5 items from the list per page and i receive the error index out of range on the last page

Viewed 109

i use this method for pagination to show 5 items from the list per page ,it works well but when the last page on the list contains less than 5 items, i receive the error lenght out of range ,what is the condition i should make to check this.

int recordsPerPage = 5;
late List<TableViewModel> currentData = [];
int currentPage = 0;

List<TableViewModel> getTableViewModelList(int pageIndex) {
currentData.clear();
currentPage = pageIndex;
if (tableViewModelList.length < 5) {
return tableViewModelList;
}
for (int i = 0; i < recordsPerPage;) {
currentData.add(tableViewModelList[i + (recordsPerPage * currentPage)]);
i++;
}
return currentData;
}

##itemCount: provider.getTableViewModelList(provider.currentPage).length,
1 Answers

first, make a variable

//productItem is the data you receive from Api calling or firebase

int recordsPerPage;

 if(productItem.length >= 5 )
    {
      recordsPerPage= 5
    }
    else
    {
    recordsPerPage= productItem.length
    }

    for (int i = 0; i < recordsPerPage;) {
    currentData.add(tableViewModelList[i + (recordsPerPage * currentPage)]);
    i++;
    }

you know that your last page don't have 5 items then you should not hard code the length. when some don't have the 5 pages then it shows what it has. like 4 , 3 or 2 items

Related