Learn how to do pagination in flutter. We will load data from rest api and using ListView.builder to show the data.
We will bring different pages and we will also define how much data to bring each time.
// main.dart
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
// Remove the debug banner
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.lightBlue,
),
home: const HomePage());
}
}
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final _baseUrl = 'https://jsonplaceholder.typicode.com/posts';
int _page = 0;
final int _limit = 20;
bool _isFirstLoadRunning = false;
bool _hasNextPage = true;
bool _isLoadMoreRunning = false;
List _posts = [];
void _loadMore() async {
if (_hasNextPage == true &&
_isFirstLoadRunning == false &&
_isLoadMoreRunning == false &&
_controller.position.extentAfter < 300
) {
setState(() {
_isLoadMoreRunning = true; // Display a progress indicator at the bottom
});
_page += 1; // Increase _page by 1
try {
final res =
await http.get(Uri.parse("$_baseUrl?_page=$_page&_limit=$_limit"));
final List fetchedPosts = json.decode(res.body);
if (fetchedPosts.isNotEmpty) {
setState(() {
_posts.addAll(fetchedPosts);
});
} else {
setState(() {
_hasNextPage = false;
});
}
} catch (err) {
if (kDebugMode) {
print('Something went wrong!');
}
}
setState(() {
_isLoadMoreRunning = false;
});
}
}
void _firstLoad() async {
setState(() {
_isFirstLoadRunning = true;
});
try {
final res =
await http.get(Uri.parse("$_baseUrl?_page=$_page&_limit=$_limit"));
setState(() {
_posts = json.decode(res.body);
});
} catch (err) {
if (kDebugMode) {
print('Something went wrong');
}
}
setState(() {
_isFirstLoadRunning = false;
});
}
late ScrollController _controller;
@override
void initState() {
super.initState();
_firstLoad();
_controller = ScrollController()..addListener(_loadMore);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Your news', style: TextStyle(color: Colors.white),),
),
body:_isFirstLoadRunning?const Center(
child: CircularProgressIndicator(),
):Column(
children: [
Expanded(
child: ListView.builder(
itemCount: _posts.length,
controller: _controller,
itemBuilder: (_, index) => Card(
margin: const EdgeInsets.symmetric(
vertical: 8, horizontal: 10),
child: ListTile(
title: Text(_posts[index]['title']),
subtitle: Text(_posts[index]['body']),
),
),
),
),
if (_isLoadMoreRunning == true)
const Padding(
padding: EdgeInsets.only(top: 10, bottom: 40),
child: Center(
child: CircularProgressIndicator(),
),
),
if (_hasNextPage == false)
Container(
padding: const EdgeInsets.only(top: 30, bottom: 40),
color: Colors.amber,
child: const Center(
child: Text('You have fetched all of the content'),
),
),
],
)
);
}
}
Pagination is all about using conditional blocks retrieve data from server.
int _page = 0;
final int _limit = 20;
bool _isFirstLoadRunning = false;
bool _hasNextPage = true;
bool _isLoadMoreRunning = false;
List _posts = [];
The above variables are at the heart of pagination. At the same time we used a base url
‘https://jsonplaceholder.typicode.com/posts’;
Your end point should support pagination. It means it should have mechanism for getting page based limited data.
Hello Dastgir,
I have go away through your tutorial for Pagination (https://learnflutter.co/flutter-pagination-listview-and-load-more-on-scroll/) but in above example I think we found one problem. The problem is like when we scroll list to down then that time old data has also been display. I think this data will not display.
Initially list displaying well up to 20 index/limit but when I scroll it down then again it will display first 20 records. I think it will not display 1st 20 records when list is scrolling.
Hope you understand my problem and help me out in that.
Thanks.
Hello Ravindra S. Patil,
Do You Find Any Solution For The Problem Of The Old Data Getting Displayed Again When We Scroll Down ?
If Yes Can You Share It With Me ?
Do You Find Any Solution For The Problem Of The Old Data Getting Displayed Again When We Scroll Down ?