0

Is there any example that I can refer to about Common class/method for flutter API calls(GET,POST,...) in flutter? I have handled all the API requests in a common method in react native, I'm not sure how to implement it in flutter.

3 Answers3

3

you have to call getRequest using url parameter

Future<Response> getRequest(String url) async {
    Response response;
    try {
      response = await _dio.get(url,
          options: Options(headers: {
            HttpHeaders.authorizationHeader:
                'Bearer $accessToken'
          }));
      print('response $response');
    } on DioError catch (e) {
      print(e.message);
      throw Exception(e.message);
    }
    return response;
  }

here is the post method

Future<Response> posRequestImage(String url, data) async {

    try {
      response = await _dio.post(
        url,
        data: formData,
        options: Options(headers: {
          HttpHeaders.authorizationHeader:
              'Bearer $accessToken'
        }),
      );
      if (response.statusCode == 200) {
        return response;
      }
      print('post response $response');
    } on DioError catch (e) {
      print(e.message);
      throw Exception(e.response?.statusMessage);
    }
    return response;
  }
Alwayss Bijoy
  • 778
  • 9
  • 15
  • Thank you! Could you please show me in the receiving end should I call this method like, Future res = getRequest(uri) ? – CHANDUKA SAMARASINGHE. Oct 25 '21 at 10:20
  • ohh you can call like this, final response = await _httpService.getRequest('$endpoint'); final getOrders = AllOrderListModel.fromJson(response.data); return getOrders; – Alwayss Bijoy Oct 25 '21 at 12:04
1

You can create a class to handle it. For example, this is my class to handle all service for user model

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

class UserService {
  var baseUrl = URL.devAddress;

  Future<User> getUser() async {
    final response = await http.get(
        Uri.parse(baseUrl + "user/1")
    );
    if (response.statusCode == 200) {
      final data = json.decode(response.body);
      return data
    } else {
      throw Exception("Failed");
    }
  }
}
Ananda Pramono
  • 899
  • 1
  • 6
  • 18
0
Future<void> getUser(String username) async {       
 Uri uri = Uri.parse('https://example.com');

try {
    Map<String, dynamic> params = new HashMap();
    params['username'] = username;

    final response = await client.post(uri,
     body: jsonEncode(params),
   );
   print("response ${response.body}");
 } on FetchDataException {
   throw FetchDataException("No Internet connection");
 }

}