How to Display API Data and Data Filters with Getx Flutter

How to Display API Data and Data Filters with Getx Flutter

Hello everyone, welcome back again at porkaone. On this occasion we will learn how to use GetX state management in a case study of creating data search filters. Are you curious? Come on, follow the tutorial below.

Getx is a Flutter state management package that is quite popular in use today. On this occasion we will learn how to display api data and filter the data obtained using state management.


    How to Display Api Data and Filter Data with Getx Flutter

    1. Create a new flutter project with the desired name. Use the latest version of flutter or flutter that supports null safety.

    2. Open the pubspec.yaml file then add the get: and http: packages. You can see how to add them in the image below. And save the file to download the required packages.

    Getx Flutter


    3. Create a new file with the name post_controller.dart in the lib folder. Follow the script as below.



    import 'dart:convert'; import 'package:get/get.dart'; import 'package:http/http.dart' as http; class PostController extends GetxController { var posts = <dynamic>[].obs; var originalPosts = <dynamic>[].obs; var searchQuery = ''.obs; @override void onInit() { super.onInit(); fetchPosts(); } Future<void> fetchPosts() async { try { var response = await http.get(Uri.parse('https://dummyjson.com/posts')); if (response.statusCode == 200) { var data = json.decode(response.body)['posts']; posts.value = data; originalPosts.value = data; print(posts); } } catch (e) { print(e); } } void searchPosts(String query) { searchQuery.value = query; if (query.isEmpty) { posts.value = originalPosts.toList(); // Menampilkan semua data } else { var filteredData = originalPosts .where((item) => item['title'] .toString() .toLowerCase() .contains(query.toLowerCase())) .toList(); posts.value = filteredData; } } }


      Explanation of the script above:
      1. import 'dart:convert';: Imports the dart:convert library which is used to encode and decode JSON data.
      2. import 'package:get/get.dart';: Imports the get library to use GetX for state management.
      3. import 'package:http/http.dart' as http;: Imports the http library to make HTTP requests to the API.
      4. class PostController extends GetxController { ... }: Defines the PostController class which is an instance of GetxController.
      5. var posts = <dynamic>[].obs;: Declares a variable.
      6. var originalPosts = <dynamic>[].obs;: Declares the originalPosts variable. This variable is used to store the original list before applying search filters.
      7. var searchQuery = ''.obs;: Declares the searchQuery variable. This variable is used to store search keywords entered by the user.
      8. void onInit() { ... }: Method called when PostController is initialized. In this method, we call fetchPosts() to fetch data from the API.
      9. Future<void> fetchPosts() async { ... }: Method used to fetch data from API using http.get() method. The received data is then decoded from JSON format using json.decode(). After that, the posts and originalPosts values ​​are updated with the received data. In this example, the posts value is printed using print().
      10. void searchPosts(String query) { ... }: Method used to search posts data based on the query (search keyword). If the query is empty, then the posts will be reorganized with the original list of originalPosts, thus displaying all the data. If the query is not empty, then a filter is performed on originalPosts based on the title using where() and contains(), and the filter results are given to posts.


      4. Open lib/main.dart then replace it with the script below.



      import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'post_controller.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return GetMaterialApp( title: 'Your App Name', theme: ThemeData( primarySwatch: Colors.blue, ), home: HomePage(), ); } } class HomePage extends StatelessWidget { final postController = Get.put(PostController()); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Your App Name'), ), body: Column( children: [ Padding( padding: const EdgeInsets.all(8.0), child: TextField( onChanged: (value) => postController.searchPosts(value), decoration: InputDecoration( labelText: 'Search', prefixIcon: Icon(Icons.search), ), ), ), Expanded( child: Obx( () { if (postController.posts.isEmpty) { return Center( child: CircularProgressIndicator(), ); } else { return ListView.builder( itemCount: postController.posts.length, itemBuilder: (context, index) { final post = postController.posts[index]; return Card( child: ListTile( leading: Image.network( 'https://cdn.pixabay.com/photo/2022/09/10/23/28/city-7445873_1280.jpg', fit: BoxFit.cover, width: 80, height: 80, ), title: Text( post['title'], maxLines: 2, overflow: TextOverflow.ellipsis, ), subtitle: Text( post['body'], maxLines: 3, overflow: TextOverflow.ellipsis, ), ), ); }, ); } }, ), ), ], ), ); } }


      5. Ok, we have done all the steps. Run the emulator and if successful, it will look like the image below

      Cara Menampilkan Data Api dan Filter Data dengan Getx Flutter  Cara Menampilkan Data Api dan Filter Data dengan Getx Flutter




      Read Another Article ✨
      📰 1. How to Display a Website in Flutter with Webview  read more
      📰 2. How to Make a Bubble Bottom Bar in Flutter read more
      📰 3. How to Install Java Development Kit and Add Variable Path to ENV read more
      📰 4. How to Make Copy Feature in Flutter Apps read more


      That's it for this tutorial on "How to Display API Data and Data Filters with Getx Flutter". Hopefully this short tutorial helps, and if you have any questions, please ask directly in the comments column below. That's all and receive a salary.

      Post a Comment

      0 Comments