Handle Api Response || Flutter GetX MVVM/MVC Pattern Tutorials in Hindi/Urudu

3 min read 6 months ago
Published on Aug 29, 2024 This response is partially generated with the help of AI. It may contain inaccuracies.

Table of Contents

Introduction

In this tutorial, we will learn how to handle API responses in Flutter using the GetX framework with the MVVM/MVC pattern. This guide is designed to help you manage different states of your API requests, including waiting for a response, handling successful requests, and managing error responses. Understanding this process is crucial for building responsive and user-friendly applications.

Step 1: Set Up Your Flutter Project

  • Create a new Flutter project or open an existing one.

  • Add the GetX package to your pubspec.yaml file:

    dependencies:
      get: ^4.6.1
    
  • Run the command to install the package:

    flutter pub get
    

Step 2: Create API Service

  • Create a new Dart file for your API service. For example, api_service.dart.

  • Define a method to fetch data from your API:

    import 'package:http/http.dart' as http;
    import 'dart:convert';
    
    class ApiService {
      Future<dynamic> fetchData(String url) async {
        final response = await http.get(Uri.parse(url));
    
        if (response.statusCode == 200) {
          return json.decode(response.body);
        } else {
          throw Exception('Failed to load data');
        }
      }
    }
    

Step 3: Set Up Controller with GetX

  • Create a controller class that will handle API calls and state management. For example, data_controller.dart.

    import 'package:get/get.dart';
    import 'api_service.dart';
    
    class DataController extends GetxController {
      var isLoading = true.obs;
      var data = [].obs;
      var errorMessage = ''.obs;
    
      void fetchData() async {
        isLoading(true);
        try {
          var response = await ApiService().fetchData('YOUR_API_URL');
          data.value = response;
        } catch (e) {
          errorMessage.value = 'Error: $e';
        } finally {
          isLoading(false);
        }
      }
    }
    

Step 4: Create the UI

  • In your main widget, use the GetX controller to manage the state.

    import 'package:flutter/material.dart';
    import 'package:get/get.dart';
    import 'data_controller.dart';
    
    class HomePage extends StatelessWidget {
      final DataController controller = Get.put(DataController());
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(title: Text('API Response Handling')),
          body: Obx(() {
            if (controller.isLoading.value) {
              return Center(child: CircularProgressIndicator());
            } else if (controller.errorMessage.isNotEmpty) {
              return Center(child: Text(controller.errorMessage.value));
            } else {
              return ListView.builder(
                itemCount: controller.data.length,
                itemBuilder: (context, index) {
                  return ListTile(title: Text(controller.data[index]));
                },
              );
            }
          }),
        );
      }
    }
    

Step 5: Initialize the Application

  • Ensure to call the fetchData method in your HomePage widget to fetch the data when the app starts.

    @override
    void initState() {
      super.initState();
      controller.fetchData();
    }
    

Conclusion

In this tutorial, we covered how to handle API responses in Flutter using GetX. We set up a Flutter project, created an API service, managed state with a GetX controller, and built a simple UI to display the data or any errors.

Next steps could include improving error handling, adding more complex data structures, or integrating more advanced features such as pagination or search functionality. By mastering these techniques, you'll be well on your way to creating robust Flutter applications.