getAges function
//////////////////////////////// ////////////////////////////////
Implementation
// For getting the age prediction data of several names...
Future<List> getAges({required List<String> names, String? apiKey}) async {
String targeturl = 'https://api.agify.io/?';
// If apiKey is not given
if (apiKey == null) {
for (var name in names) {
if (names.last == name) {
targeturl = targeturl + "name[]=$name";
} else {
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"]}";
}
}
return jsondata;
}
// if apiKey is given
for (var name in names) {
if (names.last == name) {
targeturl = targeturl + "name[]=$name";
} else {
targeturl = targeturl + "name[]=$name&";
}
}
targeturl = targeturl + "&apikey=$apiKey";
http.Response webresult = await http.get(Uri.parse(targeturl));
var jsondata = jsonDecode(webresult.body);
if (jsondata.runtimeType.toString() == "_JsonMap") {
var data = jsondata as Map;
if (data.keys.toList().contains("error")) {
throw "Error: ${data["error"]}";
}
}
return jsondata;
}