request method

Future request (
  1. String endpoint,
  2. {Map payload: const {},
  3. bool private: false,
  4. String token}
)

Implementation

Future<dynamic> request(String endpoint,
    {Map<dynamic, dynamic> payload = const {},
    bool private = false,
    String token}) async {
  var jsonData;
  final headers = {'Content-Type': 'application/json'};
  final finalUrl = _baseUrl + (private ? '/private/' : '/public/') + endpoint;
  var requestData = {};

  if (token != null) {
    requestData['payload'] = payload;
    requestData['token'] = token;
  }

  try {
    // Sending Request
    var response = await client.post(
      finalUrl,
      body: json.encode(requestData),
      headers: headers,
    );

    // Convert Response to JSON
    jsonData = json.decode(response.body.toString());
    if (response.statusCode >= 400 && response.statusCode < 500) {
      throw response.body;
    } else if (response.statusCode >= 500) {
      throw "Internal Server Error";
    }
  } catch (ex) {
    // Handeling Exception
    print("Error: " + ex.toString());
  } finally {
    client.close();
  }

  return jsonData;
}