getAge function
Implementation
Future<Map> getAge({required String name, String? apiKey}) async {
String targeturl = 'https://api.agify.io/?';
// If apiKey is not given
if (apiKey == null) {
targeturl = targeturl + "name=$name";
http.Response webresult = await http.get(Uri.parse(targeturl));
var jsondata = jsonDecode(webresult.body);
// For responses like {"error":"Invalid API key"}
if (jsondata.runtimeType.toString() == "_JsonMap") {
var data = jsondata as Map;
if (data.keys.toList().contains("error")) {
throw "Error: ${data["error"]}";
}
}
var _name = jsondata["name"];
var age = jsondata["age"];
var count = jsondata["count"];
return {"Name": _name, "Age": age, "Count": count};
}
// if apiKey is given
targeturl = targeturl + "name=$name&apikey=$apiKey";
http.Response webresult = await http.get(Uri.parse(targeturl));
var jsondata = jsonDecode(webresult.body);
// For responses like {"error":"Invalid API key"}
if (jsondata.runtimeType.toString() == "_JsonMap") {
var data = jsondata as Map;
if (data.keys.toList().contains("error")) {
throw "Error: ${data["error"]}";
}
}
var _name = jsondata["name"];
var age = jsondata["age"];
var count = jsondata["count"];
return {"Name": _name, "Age": age, "Count": count};
}