Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
33 views

API integration in Flutter Using GETX

Uploaded by

priyanshuwebplat
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

API integration in Flutter Using GETX

Uploaded by

priyanshuwebplat
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

API integration in Flutter Using GETX

here’s a step-by-step guide to define an API endpoint, make a request, store the received data in
GetX controllers, and update the UI based on the state:

1. Define API Endpoint

Let’s assume we are fetching a list of users from an API (e.g.,


https://jsonplaceholder.typicode.com/users). You can replace this with your actual API.

2. Create a Model

Create a Dart model to represent the data. For this example, let’s assume you want to store user
information (name, username, and email).

dart

class UserModel {

final String name;

final String username;

final String email;

UserModel({required this.name, required this.username, required this.email});

// Factory method to create UserModel from JSON

factory UserModel.fromJson(Map<String, dynamic> json) {

return UserModel(

name: json['name'],

username: json['username'],

email: json['email'],

);

3. Create the API Service

Define a service that makes the API request.

import 'package:http/http.dart' as http;

import 'dart:convert';

import 'user_model.dart'; // import your model


class ApiService {

static const String apiUrl = 'https://jsonplaceholder.typicode.com/users';

// Fetch data from the API

static Future<List<UserModel>> fetchUsers() async {

final response = await http.get(Uri.parse(apiUrl));

if (response.statusCode == 200) {

List<dynamic> jsonData = json.decode(response.body);

// Convert JSON to a list of UserModel

return jsonData.map((json) => UserModel.fromJson(json)).toList();

} else {

throw Exception('Failed to load users');

4. Create GetX Controller

Create a controller to manage the state of your data.

import 'package:get/get.dart';

import 'user_model.dart';

import 'api_service.dart';

class UserController extends GetxController {

var userList = <UserModel>[].obs; // Observable list

var isLoading = true.obs; // Observable loading state

// Fetch users and update the state

Future<void> fetchUsers() async {

try {

isLoading(true); // Set loading to true

var users = await ApiService.fetchUsers();


userList.value = users; // Update userList with fetched users

} finally {

isLoading(false); // Set loading to false once done

@override

void onInit() {

super.onInit();

fetchUsers(); // Fetch data when the controller is initialized

5. Update the UI Based on the Controller State

Use Obx to listen to the state changes and update the UI when the data changes.

import 'package:flutter/material.dart';

import 'package:get/get.dart';

import 'user_controller.dart'; // Import the controller

class UserScreen extends StatelessWidget {

// Initialize the UserController

final UserController userController = Get.put(UserController());

@override

Widget build(BuildContext context) {

return Scaffold(

appBar: AppBar(

title: Text('Users'),

),

body: Obx(() {

// Check if loading

if (userController.isLoading.value) {
return Center(child: CircularProgressIndicator());

} else if (userController.userList.isEmpty) {

return Center(child: Text('No users found.'));

} else {

// Display user data

return ListView.builder(

itemCount: userController.userList.length,

itemBuilder: (context, index) {

var user = userController.userList[index];

return ListTile(

title: Text(user.name),

subtitle: Text(user.username),

trailing: Text(user.email),

);

},

);

}),

);

6. Complete Setup

 Step 1: Define the UserModel class for the structure of the data.

 Step 2: Create a service (ApiService) to handle the API request and fetch the data.

 Step 3: Use a GetX controller (UserController) to manage the state and handle data fetching.

 Step 4: Update the UI in UserScreen using Obx to reactively display the fetched data.

Key Points:

 GetX Controller (UserController) manages the state of the fetched data and the loading
indicator.

 Obx widget listens to observable state changes in the controller (userController.isLoading


and userController.userList).

 ApiService is used to handle the HTTP request.


This structure allows for a clean separation of concerns, with the controller handling logic and the UI
reacting to state changes automatically.

Concept Overview

Imagine you are running a shop, and you want to display a list of items (users) on a board. The
process involves:

1. API (Shop Inventory): Think of the API as the supplier’s catalog. You request a list of available
items (users) from the supplier (API).

2. GetX Controller (Shop Manager): The controller is the shop manager who checks the
inventory (the data from the API) and stores it in the shop (your app).

3. Observable State (Shop Inventory List): The shop manager keeps a list of all items in the
inventory. If the supplier updates the catalog, the list in the shop is automatically updated
(thanks to GetX observables).

4. UI (Display Board): The board (UI) is updated based on the items in the shop's inventory. If
the shop manager (controller) updates the list, the board updates itself without you having
to refresh it.

Simple Process in Layman Terms

1. Request Data: The app requests user data from an online server (API). This is like asking for a
list of products from the supplier.

2. Store Data in Controller: Once the app receives the data, it passes the information to the
controller (the shop manager), who stores it and takes care of it.

3. Update UI Automatically: The controller tells the display board (UI) what to show based on
the data it holds. If the data changes, the board updates automatically without any extra
effort.

Flowchart

Below is a flow chart that describes this entire process step by step:

plaintext

Copy code

┌─────────────────────────────────────────────────┐

│ Start App │

└─────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────┐

│ Make Request to API (Supplier's Catalog) │


└─────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────┐

│ API Sends Data (Product List) │

└─────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────┐

│ GetX Controller Receives Data and Stores It │

└─────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────┐

│ Update UI (Display Board) Based on Stored Data │

└─────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────┐

│ Users Can See the Updated Data Automatically │

└─────────────────────────────────────────────────┘

Explanation of Flow:

1. Start App: The user opens the app.

2. Make Request to API: The app makes a request to the API to get the user data (like asking
the supplier for product details).

3. API Sends Data: The API responds with the requested data.

4. Controller Receives Data: The controller receives the data and stores it (like the shop
manager receiving and organizing products).

5. Update UI: The app’s UI (display board) automatically updates based on the data that the
controller has.

6. Users Can See Data: The user sees the updated data on the app without refreshing it.
In this flow, GetX acts like the "manager" that handles the data, while the API provides the data, and
the UI updates itself whenever the data changes!

4o

You might also like