'Extract address Component from Maps picker address

I have installed Google Maps Place Picker

which return correctly maps and I can get the right address with geolocator.

Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => PlacePicker(
          apiKey: APIKeys.apiKey,   // Put YOUR OWN KEY here.
          onPlacePicked: (result) { 
            print(result.address); 
            Navigator.of(context).pop();
          },
          initialPosition: HomePage.kInitialPosition,
          useCurrentLocation: true,
        ),
      ),
    );

now this result return return.addressComponent which should be a list of the component of the address picked. I need to get all of these value in a Map to push this data into firestore. Any help?



Solution 1:[1]

The object result.addressComponents is a type of List<AddressComponents> where in you can iterate through using for loop. Here is a sample:

Navigator.push(
   context,
   MaterialPageRoute(
      builder: (context) => PlacePicker(
         apiKey:"YOUR_API_KEY", // Put YOUR OWN KEY here.
         onPlacePicked: (result) {
              for (var i in result.addressComponents) {
                  print("Short Name: " +
                         i.shortName +
                        "Long Name: " +
                         i.longName);
              }
              Navigator.of(context).pop();
          },
          initialPosition: _MyHomePageState.kInitialPosition,
          useCurrentLocation: true,
      ),
   ),
);

The above code will list all the shortName and longName of the place that was picked which looks something like this: enter image description here

Please also be mindful of the comment from @Nelson Jr that pushing this to your data base might be in violation of the Google Maps Platform Terms of Service.

Solution 2:[2]

The object result.addressComponents is a type of List<AddressComponents> where in you can iterate through using for loop. Here is a sample:

Navigator.push(
   context,
   MaterialPageRoute(
      builder: (context) => PlacePicker(
         apiKey:"YOUR_API_KEY", // Put YOUR OWN KEY here.
         onPlacePicked: (result) {
              for (var i in result.addressComponents) {
                  if(i.types.first == "postal_code"){
                      print("here is the postal code ${i.longName}");
                 }
              }
              Navigator.of(context).pop();
          },
          initialPosition: _MyHomePageState.kInitialPosition,
          useCurrentLocation: true,
      ),
   ),
);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jabamataro
Solution 2 Ologunde Olawale