getPostalcode function

Future<Map<String, String>> getPostalcode({
  1. required String address,
  2. required String apiKey,
})

Implementation

Future<Map<String, String>> getPostalcode(
    {required String address, required String apiKey}) async {
  try {
    var rapidApiapiKey = await getApiKey(apiKey: apiKey, name: 'rapid_api');
    final http.Response response = await http.post(
        Uri.parse(
            "https://geekfeed-search-japanese-postcode-v1.p.rapidapi.com/search-address"),
        headers: <String, String>{
          'Content-Type': 'application/json',
          "X-RapidAPI-Key":
              "1d31e5443cmshd119155cdd68e8dp1536cejsn8c60c9938b42",
          "X-RapidAPI-Host": rapidApiapiKey,
        },
        body: jsonEncode({"address": address.replaceAll(' ', '')}));

    var result = jsonDecode(response.body);
    if (kDebugMode) {
      print(result);
    }

    Map<String, String> addressResult = Map<String, String>.from({
      "address1Ja": "",
      "address2Ja": "",
      "postalcode": "",
    });

    if (result.containsKey('Items')) {
      var items = result["Items"];
      items.forEach((item) {
        var attributes = item["Attributes"];

        attributes.forEach((attribute) {
          if (attribute["Name"] == "postalcode") {
            addressResult["postalcode"] = attribute["Value"];
          }
          if (attribute["Name"] == "city") {
            addressResult["address1Ja"] = attribute["Value"];
          }
          if (attribute["Name"] == "townarea") {
            addressResult["address2Ja"] = attribute["Value"];
          }
        });
      });
      if (kDebugMode) {
        print(addressResult);
      }
      return addressResult;
    }

    return addressResult;
  } catch (e) {
    if (kDebugMode) {
      print(e);
    }
    return {
      "address1Ja": "",
      "address2Ja": "",
      "postalcode": "",
    };
  }
}