I would like to have pagination in a large list of data. I have been searching for pagination in Flutter, but all of them are showing the way to use load more or lazy loading, but I would like to load data page by page. So, if I have a 100 data list, on the first page there will be a list of data from 1-10, second page: 11-20, ... Are there any resources available for me to do that?
I have given you a complete example. If you have any problem do let me know. Also, you need to check if the page is not < 0
and > max available page
.
Check demo on the action: https://dartpad.dev/?null_safety=true&id=45a5415abd0ae0fa87caac53e3b7f3e3
Gist: https://gist.github.com/omishah/45a5415abd0ae0fa87caac53e3b7f3e3
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
final String title;
MyHomePage({Key? key, required this.title}) : super(key: key);
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final List<int> _data = List.generate(100, (i) => i); // generate a sample data ( integers ) list of 100 length
int _page = 0; // default page to 0
final int _perPage = 10; // per page items you want to show
@override
Widget build(BuildContext context) {
final dataToShow =
_data.sublist((_page * _perPage), ((_page * _perPage) + _perPage)); // extract a list of items to show on per page basis
return Scaffold(
body: Column(children: [
Row(children: [
ElevatedButton(
onPressed: () => {
setState(() {
_page -= 1;
})
},
child: const Text('Prev'),
),
ElevatedButton(
onPressed: () => {
setState(() {
_page += 1;
})
},
child: const Text('Next'),
)
]),
ListView.builder(
shrinkWrap: true,
itemCount: dataToShow.length,
itemBuilder: (context, index) {
return ListTile(
title: Text('${dataToShow[index]}'),
);
},
)
]));
}
}