getStateCityFromAddressResponse method

Future<Map<String, String>?> getStateCityFromAddressResponse({
  1. required AddressDetailResponse? addressDetailResponse,
})

Implementation

Future<Map<String, String>?> getStateCityFromAddressResponse(
    {required AddressDetailResponse? addressDetailResponse}) async {
  if (addressDetailResponse?.status != 'OK' ||
      addressDetailResponse?.results == null ||
      (addressDetailResponse?.results?.isEmpty ?? true)) {
    return null;
  }

  final addressComponents =
      addressDetailResponse?.results?.first.addressComponents;

  String? state;
  String? city;

  if (addressComponents != null) {
    for (var component in addressComponents) {
      List<String>? types = component.types;

      if (types?.contains('administrative_area_level_1') ?? false) {
        state = component.longName;
      }

      if (types?.contains('administrative_area_level_3') ?? false) {
        city = component.longName;
      }
      if (city == null && (types?.contains('locality') ?? false)) {
        city = component.longName;
      }
      if (city == null &&
          (types?.contains('administrative_area_level_2') ?? false)) {
        city = component.longName;
      }
    }
    if (state != null && city != null) {
      return {'state': state, 'city': city};
    }
  }
  return null;
}