How to implement the pagination in flutter?
class PaginationDemo extends StatefulWidget {
const PaginationDemo({Key? key}) : super(key: key);
@override
_PaginationDemoState createState() => _PaginationDemoState();
}
class _PaginationDemoState extends State<PaginationDemo> implements PaginationInterFace{
PaginationPresenter? paginationPresenter;
int limit=10;
int page=1;
List<AllPostData> allPosts=[];
bool isLoading =false;
@override
void initState() {
paginationPresenter=PaginationPresenter(this);
setState(() {
isLoading=true;
});
paginationPresenter?.doGetData(page.toString(),limit.toString());
super.initState();
}
@override
Widget build(BuildContext context) {
returnScaffold(
body: Stack(
children: [
NotificationListener<ScrollNotification>(
onNotification: _onNotification,
child: ListView.builder(
itemCount:allPosts.length,
itemBuilder:
(BuildContext
context,
int index){
return Container(
margin: EdgeInsets.all(40),
child: Text(allPosts[index].caption.toString()));
}
),
),
Visibility(
visible: isLoading,
child: Container(
color: Colors.transparent,
width:MediaQuery.of(context).size.width,
height:MediaQuery.of(context).size.height,
alignment: Alignment.center,
child: const CircularProgressIndicator(
valueColor:
AlwaysStoppedAnimation<Color>(Colors.black54),
),
))
],
),
);
}
bool _onNotification(ScrollNotification notification) {
if (notification is ScrollEndNotification &&
notification.metrics.pixels >=
notification.metrics.maxScrollExtent - 200) {
fetchData();
}
return true;
}
Future<void> fetchData() async {
if (isLoading) return;
setState(() {
isLoading = true;
});
// Simulating API request with a delay
await Future.delayed(Duration(seconds: 2));
int count=page++;
paginationPresenter?.doGetData(count.toString(),limit.toString());
}
@override
onError(String msg, int status) {
setState(() {
isLoading=false;
});
if (kDebugMode) {
print("onError${msg}");
}
}
@override
onSuccess(AllPostResponse allPostResponse) {
setState(() {
isLoading=false;
});
if (kDebugMode) {
print("Success${allPostResponse.status}");
}
if (allPostResponse.status == 200) {
allPosts.addAll(allPostResponse.data!);
}
}
}
/////// add parameter in int bool etc
Future<AllPostResponse> registerAPI(String isPhone,) async {
Map<String, dynamic> requestBody = {
"isPhone":false,};
String jsonBody=json.encode(requestBody);
// Set the headers
Map<String, String> headers = {
'Content-Type': 'application/json',
};
return _netUtil.postApi("", body: jsonBody,headers: headers).then((dynamic res) {
return AllPostResponse.fromJson(res);
});
}