StreetAddress.fromGeocodingResult constructor

StreetAddress.fromGeocodingResult(
  1. GeocodingResult geocodingResult
)

Implementation

factory StreetAddress.fromGeocodingResult(GeocodingResult geocodingResult) {
  if (!geocodingResult.types.contains('street_address')) {
    throw ArgumentError.value('street_address type not found in result');
  }

  AddressComponent? search(String type) {
    try {
      return geocodingResult.addressComponents.firstWhere(
        (component) => component.types.contains(type),
      );
    } on StateError catch (_) {
      return null;
    }
  }

  final country = search('country');

  return StreetAddress(
    geometry: geocodingResult.geometry,
    addressLine: geocodingResult.formattedAddress,
    countryName: country?.longName,
    countryCode: country?.shortName,
    featureName:
        search('featureName')?.longName ?? geocodingResult.formattedAddress,
    postalCode: search('postal_code')?.longName,
    adminArea: search('administrative_area_level_1')?.longName,
    subAdminArea: search('administrative_area_level_2')?.longName,
    locality: search('locality')?.longName,
    subLocality:
        (search('sublocality') ?? search('sublocality_level_1'))?.longName,
    thoroughfare: search('route')?.longName,
    subThoroughfare: search('street_number')?.longName,
  );
}