I'm currently implementing pagination using pagewise package. But to use the pagecontroller
, I have to define a static controller and static future function that will connect to my api using http. My problem is, I also need the current user id as a parameter in my API request retrieved using provider. And I also need the BuildContext to show dialog box on API request return. Is it ok to save the id and context globally or outside the class just like the sample code below? Please teach me how to do this the correct way.
int id;
BuildContext currentContext;
class MyWidgetView extends StatefulWidget {
@override
_MyWidgetViewState createState() => _MyWidgetViewState();
}
class _MyWidgetViewState extends State<MyWidgetView> {
bool _empty = false;
@override
void initState() {
super.initState();
currentContext = context;
id = Provider.of<User>(context, listen: false).id;
this._pageLoadController.addListener(() {
if (this._pageLoadController.noItemsFound) {
setState(() {
this._empty = this._pageLoadController.noItemsFound;
});
}
});
}
final _pageLoadController = PagewiseLoadController(
pageSize: PAGE_SIZE, pageFuture: (pageIndex) => getPage(pageIndex));
static Future<List<page>> getPage(int pageIndex) async {
final APIService _pageService = APIService();
final pages = await _pageService.getPage(id: id);
if (pages.error == false) {
return pages.data;
} else {
dialogBox(
title: 'Error',
message: pages.errorMessage,
context: currentContext,
isModal: true,
function: () => Navigator.pop(currentContext));
}
}
That static
is a rabbit hole you should not follow. Just don't make it static
in the first place.
PagewiseLoadController _pageLoadController;
@override
void initState() {
super.initState();
_pageLoadController = PagewiseLoadController(pageSize: PAGE_SIZE, pageFuture: (pageIndex) => getPage(pageIndex));
// rest of your method here
}
Now your getPage
method can be a normal, non-static class method.