Search code examples
fluttergoogle-apigoogle-places-apiautofill

Flutter Google Address Autofill


I want an up to date example on how to add autofill addresses in flutter. I have looked at every resource I can and some people over complicate the heck out of it,or just copy and paste different messy code. Atm I have a Google search that just shows a blue line as if Its waiting and gets no response.

TextFormField(
                controller: addressController,
                onTap: () async {
                  Prediction p = PlacesAutocomplete.show(
                          context: context,
                          apiKey: "MY_API_KEY_SECRET_SHHHHHH",
                          mode: Mode.fullscreen,
                          language: "En",
                          components: [new Component(Component.country, "NZ")])
                      as Prediction;
                  displayPrediction(p);
                },
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return "Customer must have address! cannot be blank";
                  }
                },
                decoration: InputDecoration(
                  hintText: "Enter Customer Address",
                  border: OutlineInputBorder(),
                  prefixIcon: Icon(Icons.map),
                ),
              ),

and I also have displayPrediction

Future<Null> displayPrediction(Prediction p) async {
  GoogleMapsPlaces _places = GoogleMapsPlaces(
    apiKey: "API_KEY",
    apiHeaders: await GoogleApiHeaders().getHeaders(),
  );
  PlacesDetailsResponse detail =
      await _places.getDetailsByPlaceId(p.placeId.toString());
  final lat = detail.result.geometry!.location.lat;
  final lng = detail.result.geometry!.location.lng;
}
Broken Search Example

Solution

  • So my problem was solved within the Prediction method. here is how I solved it with help from other resources.

    Prediction? p = await PlacesAutocomplete.show(
            context: context,
            apiKey: kGoogleApiKey,
            radius: 10000000,
            types: [],
            strictbounds: false,
            mode: Mode.overlay,
            decoration: InputDecoration(
              hintText: 'Search',
              focusedBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(20),
                borderSide: BorderSide(
                  color: Colors.white,
                ),
              ),
            ),
            components: [Component(Component.country, "nz")],
          );