getAgesWithCountry function

Future<List> getAgesWithCountry({
  1. required List<String> names,
  2. required String country,
  3. String? apiKey,
})

//////////////////////////////// ////////////////////////////////

Implementation

// For getting the age prediction data of several names but with country...

Future<List> getAgesWithCountry(
    {required List<String> names,
    required String country,
    String? apiKey}) async {
  String targeturl = 'https://api.agify.io/?';

  if (apiKey == null) {
    for (var name in names) {
      if (names.last == name) {
        targeturl = targeturl + "name[]=$name";
      } else {
        targeturl = targeturl + "name[]=$name&";
      }
    }

    targeturl = targeturl + "&country_id=$country";

    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 + "&country_id=$country&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;
}