postData static method

Future postData({
  1. required String url,
  2. required Map<String, dynamic> body,
  3. Map<String, String> header = const {'Content-Type' : 'application/json'},
})

Implementation

static Future<dynamic> postData({
  required String url,
  required Map<String, dynamic> body,
  Map<String, String> header = const {'Content-Type': 'application/json'},
}) async {
  try {
    Response response = await post(
      Uri.parse(url),
      body: jsonEncode(body),
      headers: header,
    );

    log('POST status: ${response.statusCode}');

    if (response.statusCode == 200) {
      // Check if response body is not empty and is valid JSON
      if (response.body.isNotEmpty) {
        return jsonDecode(response.body);
      }
      return null;
    }
    throw ApiFailedException(msg: 'failed to post the data :(');
  } on ApiFailedException catch (e) {
    log(e.toString());
    return null;
  }
}