skip to Main Content

I want to create a common API class so I can call that API class for every API and get data.

I have tried but failed to get common response from API class. So now I am here to get some help from my stackoverflow team.

Thank you in advance

2

Answers


  1. Chosen as BEST ANSWER
    import 'dart:convert';
    import 'dart:developer';
    
    import 'package:http/http.dart' as http;
    import'package:windexprcticalusing_riverpod/application/dialog/dialod_service.dart';
    import 'package:windexprcticalusing_riverpod/utils/appcolors.dart';
    
    class ApiClient {
    ApiClient();
    
    Map<String, String> createHeaders() {
     final headers = <String, String>{
      'Content-Type': 'application/json',
      };
    
    return headers;
    }
    
    Future<T?> postData<T>({
    required Uri uri,
    required var headers,
    required var body,
    required T Function(dynamic data) builder,
    }) async {
    try {
      print("_postData URL=-=-=-=-::: $uri");
      print("_postData headers=-=-=-=-::: $headers");
      print("_postData body=-=-=-=-::: $body");
      var request = http.Request('POST', uri);
      request.body = json.encode(body);
      print('_postData $uri body ${request.body}');
      request.headers.addAll(headers);
    
      http.StreamedResponse response = await request.send();
      final responseString = await response.stream.bytesToString();
    
      String newwresponse = responseString.replaceAll('{"d":null}', '');
      if (response.statusCode == 200 || response.statusCode == 201) {
        print('response.statusCode is ${response.statusCode}');
    
        log("response is=-=- ${responseString}");
        return builder(newwresponse);
      } else {
        DialogServiceV1().showSnackBar(
            content: response.reasonPhrase.toString(),
            color: AppColors.appprimarycolor.withOpacity(0.7),
            textclr: AppColors.white);
        print(response.reasonPhrase);
        return null;
      }
    } catch (e) {
      DialogServiceV1().showSnackBar(
          content: e.toString(),
          color: AppColors.appprimarycolor.withOpacity(0.7),
          textclr: AppColors.white);
      throw Exception("Exception is =-=-1 $e");
    }
    }
    
    Future<T?> multipartData<T>({
    required Uri uri,
    required var headers,
    required var body,
    required T Function(dynamic data) builder,
    required var imageparam,
    required var imagepath,
    }) async {
    try {
      print("_multipartData URL=-=-=-=-::: $uri");
      print("_multipartData headers=-=-=-=-::: $headers");
      print("_multipartData body=-=-=-=-::: $body");
      var request = http.MultipartRequest('POST', uri);
      request.fields.addAll(body);
      print('_multipartData $uri body ${request.fields}');
      request.files
          .add(await http.MultipartFile.fromPath(imageparam, imagepath));
      request.headers.addAll(headers);
    
      http.StreamedResponse response = await request.send();
      if (response.statusCode == 200 || response.statusCode == 201) {
        print('response.statusCode is ${response.statusCode}');
        final responseString = await response.stream.bytesToString();
        log("response is=-=-${responseString}");
        return builder(responseString);
      } else {
        print(response.reasonPhrase);
        return null;
      }
    } catch (e) {
      DialogServiceV1().showSnackBar(
          content: e.toString(),
          color: AppColors.red.withOpacity(0.7),
          textclr: AppColors.white);
      throw Exception("Exception is =-=-2 $e");
      }
     }
    }
    

  2. Create a file called api_service.dart.

    Inside api_service.dart, import the necessary packages:

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

    Create a class called ApiService that will contain the common API methods:

    class ApiService {
      static const String baseUrl = 'https://api.domain.com'; // Replace with your API base URL
    
      // methods here
    }
    

    Below is full api_service.dart code:

    class ApiService {
      static const String baseUrl = 'https://api.example.com'; // Replace with your API base URL
    
      static Future<dynamic> get(String endpoint) async {
        final response = await http.get(Uri.parse('$baseUrl/$endpoint'));
    
        if (response.statusCode == 200) {
          return json.decode(response.body);
        } else {
          throw Exception('Failed to load data');
        }
      }
    }
    

    How to use:

    import 'package:flutter/material.dart';
    import 'api_service.dart';
    
    void fetchData() async {
      try {
        final data = await ApiService.get('users'); // Replace 'users' with your desired API endpoint
        print('API response: $data');
      } catch (e) {
        print('Error fetching data: $e');
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search