1

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 Answers 3

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;
  }
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! Could you please show me in the receiving end should I call this method like, Future<Response> res = getRequest(uri) ?
ohh you can call like this, final response = await _httpService.getRequest('$endpoint'); final getOrders = AllOrderListModel.fromJson(response.data); return getOrders;
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");
    }
  }
}

Comments

1
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");
 }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.