get<T> method

Future<T?> get<T>(
  1. String key
)

Implementation

Future<T?> get<T>(String key) async {
  // async, await
  if (_url == null) throw Exception('CMDB needs to be initialize');
  final response = await http.get(Uri.parse(_url! + '/' + key + '.json'));
  if (response.statusCode == 200) {
    var jsonResponse = jsonDecode(response.body);
    if (jsonResponse == null) {
      print('Field is empty');
      return null;
    }
    print(jsonResponse);
    switch (T.toString().split('<')[0]) {
      case "Map":
        return jsonResponse;
      case "List":
        List<Map<String, dynamic>> list = [];
        for (String key in jsonResponse.keys) {
          list.add(jsonResponse[key] as Map<String, dynamic>);
        }
        return list as T;
      case "String":
        return jsonResponse as T;
      default:
        print(
            'This type is not allow. It can be only returned String, Map or List type');
        return null;
    }
  } else {
    print('Request failed with status: ${response.statusCode}.');
    return null;
  }
}