Pagination using GetX in Flutter
Hello flutter developer, In this blog, we shall discuss how we can use GetX
the package for managing the state of pagination. Pagination is also known as paging, is the process of dividing a document into discrete pages. Today in most of the apps we see this feature. It helps in improving the performance of the app. Through pagination we can reduce the read request to our database, hence it reduces the cost of database maintenance. It is a user-friendly feature, interested users can scroll more and more if they deliberately want to load more data.
In this blog, we shall learn how we can implement pagination using GetX
the package. We will build an app that will display a fixed number of items and on scrolling more data will be loaded and displayed on the screen in real-time.
Table of contents:
Installing Getx
in Flutter project
Initialize the required objects
Creating a method executed every time the scroll limit exceeds its limit
Initializing HomePageController object
Introduction to GetX
:
GetX
is a state management helper package.
- It provides us a powerful and reactive state management technique, route management, and dependency Injection.
- PRODUCTIVITY, PERFORMANCE, AND ORGANIZATION are the three basic principal of the package.
- It eliminates the dependency on the widget tree.
- For routing, GetX does not need the context for navigation.
- Automatically reduce the memory consumption when the resources are not used by default.
GetX
uses its own dependency injection feature.- Simple syntax.
Installing Getx
in Flutter project:
get | Flutter Package
Languages: English (this file), Indonesian, Urdu, Chinese, Brazilian Portuguese, Spanish, Russian, Polish, Korean…pub. dev
Add Get to your pubspec.yaml
file:
dependencies:
get: ^4.1.4
Import get
in files that it will be used:
import 'package:get/get.dart';
Pagination Using GetX
:
GetMaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.red,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
)
GetMaterialApp
is a widget that is a substitute for MaterialApp
. Using this widget is not compulsory if you are using the GetX
package only for state management, but if you are using GetX
for routing then we need to use GetMaterialApp
widget.
What do we want?
We want to build an app that displays a list of items and every time the screen scroll it should automatically add some items to the existing list and update the UI in real-time.
Creating a model class:
We have created a very simple model class that has a name property.
class Model {
String name;
Model({
this.name,
});
}
Creating GetxController:
GetxController is a class in which we write all our business logic, variables, and methods used for managing the state of the app screen.
- It automatically disposes of all the controllers when the screen is popped out of the stack.
- All the processing logic will be written inside this controller.
- Like
initState()
anddispose()
methodGetX
provides usonInit()
andonClose()
. onReady()
is called after the widget is rendered on screen.update()
rebuilds theGetBuilder
associated with theGetxController
. It is similar tonotifyListeners()
in providers.onInit()
: called after the widget is allocated memory.onClose()
called just before the controller is deleted from memory.
class HomePageController extends GetxController {
}
We can create a GetxController
by extending the class with GetxController
like above.
Initialize the required objects:
We need ScrollController
to listen to the scrolling of the screen.
list
is a list of Models that will be used to map it with the list of widgets.
class HomePageController extends GetxController {
List<Model> list = [];
ScrollController controller = ScrollController();
int listLength = 6;
}
Generating initial list:
Here we have generated a list of Model
that we will initially display on the screen. List.generate()
takes an integer and function with an integer value. It will add Model
for each index in the list
.
generateList() {
list = List.generate(
listLength, (index) => Model(name: (index + 1).toString()));
}
Creating a method executed every time the scroll limit exceeds its limit:
This method will be executed every time the scroll limit exceeds its limit.
To measure the scroll limit we use the ScrollController
. maxScrollExtent
is the number of max pixels and pixels
notify when the listener when the pixel changes. controller.position.maxScrollExtent == controller.position.pixels
this condition will only return true when the scrolling is max.
addItems() async {
controller.addListener(() {
if (controller.position.maxScrollExtent == controller.position.pixels) {
for (int i = 0; i < 2; i++) {
listLength++;
list.add(Model(name: (listLength).toString()));
update(); //update GetBuilder each time
}
}
});
}
Initializing onInit() method:
This method is called before the widget build.
void onInit() {
generateList();
addItems();
super.onInit();
}
Initializing HomePageController object:
Initialize the HomePageController object in the class where you want to implement the pagination.
Get.put()
makes the object available to the child of the widgets and using Get.find()
we can find the same object in other classes as well.
HomePageController homePageController = Get.put(HomePageController());
Using GetBuilder:
GetBuilder
is rebuilt every time the update()
the method is called. It takes the init controller. It takes a builder that returns a Widget. The methods and objects can be accessed using the value
. We use the ListView.builder
to display the list of widgets. Controller of ListView.builder
will be the ScrollController
.
GetBuilder(
init: homePageController,
builder: (value) => ListView.builder(
controller: value.controller,
itemCount: value.list.length,
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
color: Colors.red,
height: 100,
child: Center(
child: Text(value.list[index].name),
),
),
);
},
),
),
You might be thinking that here we do not need the GetBuilder
as the method of homePageController
can be accessed without it as well, yes it is true but in this case, the UI will not be updated, the 2 Model
will be added into the list
an object that we have created in the HomePageController
using the addItems()
method. To change the UI we need to use GitBuilder if we are using get for state management as it is rebuilt every time the update()
the method is called.
main. dart:
https://gist.github.com/anmolgupta-aeologic/2f1367ce273685b9d76a9553b9722797
homepage_controller.dart:
https://gist.github.com/anmolgupta-aeologic/bb35406fedeeb5ba018d3d7fda1e389e
🌸🌼🌸 Thank you for reading. 🌸🌼🌸
Feel free to connect with us:
And read more articles from FlutterDevs.com
FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app 987tr project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter-related queries.
We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences!.