Skip to content

Instantly share code, notes, and snippets.

@omishah
Last active March 24, 2022 04:48
Show Gist options
  • Save omishah/45a5415abd0ae0fa87caac53e3b7f3e3 to your computer and use it in GitHub Desktop.
Save omishah/45a5415abd0ae0fa87caac53e3b7f3e3 to your computer and use it in GitHub Desktop.
Flutter - ListView with pagination
// @author OMi Shah
// @email [email protected]
// @organization CodeCyan
// @website www.codecyan.com
import 'package:flutter/material.dart';
void main() => runApp(CodeCyanApp());
class CodeCyanApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
final String title;
const 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]}'),
);
},
)
]));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment