I have an application where I push a single place_id to the Google Place Details API. The API returns the place details correctly, but I am having problems converting that information into a Address Data type. I am trying to use a custom fuction but am a new coders so it has been challenging. I am sure ths is a simple problem but being new it is daunting.
The Data Type is called address and has the fields, street, city, state, country, and postalCode. Street shoudl include both the street number and name for the address.
A sample Google Place Detsil return I am using is as follows:
{html_attributions: [], result: {address_components: [{long_name: 32, short_name: 32, types: [street_number]}, {long_name: Holton Street, short_name: Holton St, types: [route]}, {long_name: Woburn, short_name: Woburn, types: [locality, political]}, {long_name: Middlesex County, short_name: Middlesex County, types: [administrative_area_level_2, political]}, {long_name: Massachusetts, short_name: MA, types: [administrative_area_level_1, political]}, {long_name: United States, short_name: US, types: [country, political]}, {long_name: 01801, short_name: 01801, types: [postal_code]}, {long_name: 5205, short_name: 5205, types: [postal_code_suffix]}], formatted_address: 32 Holton St, Woburn, MA 01801, USA, geometry: {location: {lat: 42.4748531, lng: -71.1320983}, viewport: {northeast: {lat: 42.4762311802915, lng: -71.13095866970848}, southwest: {lat: 42.4735332197085, lng: -71.1336566302915}}}}, status: OK}
Thanks in advance for any help!
The current code I have written (that is failing):
AddressStruct googleToAddress(String? jsonResult) {
/// MODIFY CODE ONLY BELOW THIS LINE
String? streetNumber;
String? streetName;
String? city;
String? state;
String? country;
String? postalCode;
// Google place Details JSON response into a data type with all address fields
final Map<String, dynamic> json = jsonDecode(jsonResult!);
final List<dynamic> results = json['results'];
for (final component in results) {
final List<dynamic>? types = component['types'];
final String longName = component['long_name'] ?? '';
if (types is List && types.isNotEmpty) {
final String type = types.first;
if (type == 'street_number') {
streetNumber = longName;
} else if (type == 'route') {
streetName = longName;
} else if (type == 'locality') {
city = longName;
} else if (type == 'administrative_area_level_1') {
state = longName;
} else if (type == 'postal_code') {
postalCode = longName;
} else if (type == 'country') {
country = longName;
}
}
}
return createAddressStruct(
street: '$streetNumber $streetName',
city: city,
state: state,
country: country,
postalCode: postalCode,
);
/// MODIFY CODE ONLY ABOVE THIS LINE
}