Getx Pagination
Implementing pagination in Flutter applications is a common requirement when dealing with large datasets, such as lists fetched from an…
Getx Pagination
Implementing pagination in Flutter applications is a common requirement when dealing with large datasets, such as lists fetched from an API. Pagination improves performance and user experience by loading data in chunks rather than all at once. In this article, we’ll explore how to implement pagination using GetX, a lightweight and powerful state management library for Flutter. By the end, you’ll have a clear understanding of how to set up pagination with GetX, complete with a practical example.
Why Use GetX for Pagination?
GetX is a popular Flutter package that simplifies state management, dependency injection, and route management. Its reactive programming model, powered by Rx observables, makes it an excellent choice for handling dynamic data like paginated lists. Key benefits include:
- Simplicity: GetX reduces boilerplate code compared to other state management solutions.
- Reactivity: Automatically updates the UI when data changes.
- Performance: Efficiently manages resources with minimal overhead.
Prerequisites
Before diving in, ensure you have:
- Flutter SDK installed (version 3.0 or later recommended).
- A basic understanding of Flutter and Dart.
- The get package added to your pubspec.yaml.
Add GetX to your project by including the following dependency:
dependencies:
get: ^4.6.5
Run flutter pub get to install the package.
Understanding Pagination
Pagination involves fetching data in smaller, manageable chunks (pages) rather than loading the entire dataset at once. Typically, you:
- Fetch an initial page of data (e.g., 10 items).
- Load more data when the user scrolls to the bottom of the list or clicks a “Load More” button.
- Handle loading states and errors gracefully.
With GetX, we can manage the state of the paginated data (e.g., items, loading status, and page number) using a controller.
Setting Up Pagination with GetX
We’ll build a simple app that fetches a paginated list of items from a mock API and displays them in a ListView. When the user scrolls to the bottom, more items are loaded automatically.
Step 1: Create the GetX Controller
The controller will handle the logic for fetching data, managing pagination state, and updating the UI reactively. Here’s the implementation:
import 'package:get/get.dart';
class PaginationController extends GetxController {
// Reactive variables
var items = <String>[].obs; // List to hold items
var isLoading = false.obs; // Loading state
var page = 1.obs; // Current page
var hasMore = true.obs; // Flag to check if more data is available
// Simulated API call to fetch paginated data
Future<void> fetchItems() async {
if (!hasMore.value || isLoading.value) return;
isLoading.value = true;
// Simulate network delay
await Future.delayed(Duration(seconds: 1));
// Mock API response: Generate 10 items per page
final newItems = List.generate(10, (index) => 'Item ${((page.value - 1) * 10) + index + 1}');
// Check if there are more items to load
if (newItems.isEmpty) {
hasMore.value = false;
} else {
items.addAll(newItems);
page.value++;
}
isLoading.value = false;
}
@override
void onInit() {
super.onInit();
fetchItems(); // Load the first page when the controller is initialized
}
}
Explanation:
- items: An observable list (RxList) to store the fetched items.
- isLoading: Tracks whether data is being fetched to prevent multiple simultaneous requests.
- page: Keeps track of the current page number.
- hasMore: Indicates whether more data is available to fetch.
- fetchItems: Simulates an API call, appending new items to the list and incrementing the page number.
Step 2: Create the UI with a Scrollable List
We’ll create a ListView that displays the items and triggers pagination when the user scrolls to the bottom. We’ll use a ScrollController to detect when the user reaches the end of the list.
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'pagination_controller.dart';
class PaginationView extends StatelessWidget {
@override
Widget build(BuildContext context) {
// Initialize the controller
final PaginationController controller = Get.put(PaginationController());
// Create a ScrollController to detect scroll position
final ScrollController scrollController = ScrollController();
// Add listener to detect when the user scrolls to the bottom
scrollController.addListener(() {
if (scrollController.position.pixels == scrollController.position.maxScrollExtent) {
controller.fetchItems();
}
});
return Scaffold(
appBar: AppBar(
title: Text('GetX Pagination Example'),
),
body: Obx(() => ListView.builder(
controller: scrollController,
itemCount: controller.items.length + (controller.hasMore.value ? 1 : 0),
itemBuilder: (context, index) {
// Display loading indicator at the bottom
if (index == controller.items.length && controller.hasMore.value) {
return Center(
child: Padding(
padding: EdgeInsets.all(16.0),
child: CircularProgressIndicator(),
),
);
}
// Display list item
return ListTile(
title: Text(controller.items[index]),
);
},
)),
);
}
}
Explanation:
- Get.put(PaginationController()): Initializes and injects the controller using GetX’s dependency injection.
- ScrollController: Listens for scroll events to trigger fetchItems when the user reaches the bottom.
- Obx: A GetX widget that rebuilds when observable variables (e.g., items, hasMore) change.
- ListView.builder: Builds the list dynamically, adding a loading indicator at the bottom if more data is available.
Step 3: Update the Main App
To use the PaginationView, update your main app to display it:
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'pagination_view.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return GetMaterialApp(
title: 'GetX Pagination',
theme: ThemeData(primarySwatch: Colors.blue),
home: PaginationView(),
);
}
}
How It Works
- When the app starts, the PaginationController is initialized and fetches the first page of items.
- The ListView displays the items reactively using Obx.
- When the user scrolls to the bottom, the ScrollController triggers fetchItems, which appends more items to the list.
- A loading indicator is shown while fetching new data, and it disappears when hasMore is false or when the fetch completes.
Handling Real APIs
In a real-world scenario, replace the mock API logic in fetchItems with an actual API call using a package like http. Here’s an example:
import 'package:get/get.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
class PaginationController extends GetxController {
var items = <String>[].obs;
var isLoading = false.obs;
var page = 1.obs;
var hasMore = true.obs;
Future<void> fetchItems() async {
if (!hasMore.value || isLoading.value) return;
isLoading.value = true;
try {
final response = await http.get(Uri.parse('https://api.example.com/items?page=$page'));
if (response.statusCode == 200) {
final newItems = jsonDecode(response.body)['items'] as List;
if (newItems.isEmpty) {
hasMore.value = false;
} else {
items.addAll(newItems.map((item) => item['name'].toString()));
page.value++;
}
} else {
Get.snackbar('Error', 'Failed to fetch items');
}
} catch (e) {
Get.snackbar('Error', 'An error occurred: $e');
} finally {
isLoading.value = false;
}
}
@override
void onInit() {
super.onInit();
fetchItems();
}
}
Add the http package to your pubspec.yaml
dependencies:
http: ^0.13.5
Best Practices
- Debouncing: Add a debounce mechanism to prevent rapid API calls during fast scrolling.
- Error Handling: Always handle errors gracefully and inform the user via Get.snackbar or similar.
- Pull-to-Refresh: Use a RefreshIndicator widget to allow users to manually refresh the list.
- Optimization: Use ListView.builder for large lists to ensure efficient rendering.
Conclusion
Pagination with GetX in Flutter is straightforward and efficient thanks to its reactive state management. By combining a GetXController with a ScrollController, you can create a seamless pagination experience that scales with your app’s needs. The example above provides a foundation you can extend with real API calls, custom UI, and additional features like pull-to-refresh.
Try implementing this in your next Flutter project, and let GetX handle the heavy lifting of state management!
This article provides a complete guide to implementing pagination with GetX, including reusable code snippets. You can copy the code from the artifacts and adapt it to your needs. For real-world use, replace the mock API with your actual endpoint and add any additional features like error retry or caching as needed. Let me know if you need help integrating this into your project!
If you found this tutorial helpful, please give it a clap 👏 and follow for more Flutter + Supabase content!
메타데이터
- post_id
- f6757f112ee8
- slug
- getx-pagination-f6757f112ee8
- url
- https://medium.com/@saiyedmscit16/getx-pagination-f6757f112ee8
- canonical_url
- https://medium.com/@saiyedmscit16/getx-pagination-f6757f112ee8
- author_url
- https://medium.com/@saiyedmscit16
- status
- ok
- fetched_at
- 2026-06-13 12:55:53