Sitemap
Axiftaj

Axiftaj

Hello, this is Asif Taj a tech enthusiasts providing the quality services for the Android and iOS apps development, UI/UX Research and Designs, and Video ads.

Integrating Google Autocomplete Places API in Flutter Without External Packages: A Comprehensive Guide

4 min readJan 31, 2024
Press enter or click to view image in full size

Source code: https://github.com/axiftaj/Flutter-Google-Map-Tutorials/tree/main

Google Autocomplete Places API offers a robust solution for integrating location suggestions and predictions seamlessly. While there are packages available for integrating this functionality but understanding the underlying API calls can empower developers with greater control and customisation. In this guide, we’ll explore the process of implementing Google Autocomplete Places API directly in Flutter without relying on external packages.

Prerequisites: Before we proceed, ensure you have the following prerequisites:

  • Flutter SDK installed
  • Android Studio or VS CODE
  • Google Cloud Platform (GCP) account with billing enabled and the Places API enabled

Step 1: Set Up Google Cloud Platform Project

  1. Navigate to the Google Cloud Platform Console: https://console.cloud.google.com/
  2. Create a new project or select an existing one as shown in screenshot
Press enter or click to view image in full size

3. Enable the Google Places API for your project. Go to the API Library, search for “Places API,” and enable it.

Click on hamburger icon top left corner, the select API’s and services > library and then click on Place API as you can bottom right corner.

Press enter or click to view image in full size

Once you enable it this is how it will look like

Press enter or click to view image in full size

4. Create API credentials by navigating to the “Credentials” tab and selecting “Create Credentials.” Choose “API Key” and follow the instructions to generate your API key.

Get Axiftaj’s stories in your inbox

Join Medium for free to get updates from this writer.

Click on hamburger icon top left corner, the select API’s and services > Credentials and then click on CREATE CREDENTIALS and select API Key, this will generate you API key, please don’t share it with anyone.

Press enter or click to view image in full size

Let’s create Flutter project and add these packages

uuid: ^4.3.3
http:

uuid package will be used to manage session(I will explain what is session at the end)

Code explanation:

First we have created controller to to take input from user using Text Field and store it. Second we have initialise uuid instance, it helps us generate new sessions. Then in initState() method we are listening controller for changes if user type anything and calling getSuggestion(_controller.text) functions.

In _placeList, we will store the auto places suggestions to show it on screen for a success API call.

final _controller =  TextEditingController();
var uuid = const Uuid();
String _sessionToken = '1234567890';
List<dynamic> _placeList = [];

@override
void initState() {
super.initState();
_controller.addListener(() {
_onChanged();
});
}

_onChanged() {
if (_sessionToken == null) {
setState(() {
_sessionToken = uuid.v4();
});
}
getSuggestion(_controller.text);
}

getSuggestion Function:

In this function we are using http package and sending our input request to google server, when it is successful we are storing that data in array and showing it on screen by refreshing the view.

Please do store the api key in secure storage or follow other good practices so it don’t get missused.

void getSuggestion(String input) async {


const String PLACES_API_KEY = "";

try{
String baseURL = 'https://maps.googleapis.com/maps/api/place/autocomplete/json';
String request = '$baseURL?input=$input&key=$PLACES_API_KEY&sessiontoken=$_sessionToken';
var response = await http.get(Uri.parse(request));
var data = json.decode(response.body);
if (kDebugMode) {
print('mydata');
print(data);
}
if (response.statusCode == 200) {
setState(() {
_placeList = json.decode(response.body)['predictions'];
});
} else {
throw Exception('Failed to load predictions');
}
}catch(e){
print(e);
}

}

Complete source code:

import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:uuid/uuid.dart';
import 'package:http/http.dart' as http;

class GoogleMapSearchPlacesApi extends StatefulWidget {
const GoogleMapSearchPlacesApi({Key? key}) : super(key: key);


@override
_GoogleMapSearchPlacesApiState createState() => _GoogleMapSearchPlacesApiState();
}

class _GoogleMapSearchPlacesApiState extends State<GoogleMapSearchPlacesApi> {


final _controller = TextEditingController();
var uuid = const Uuid();
String _sessionToken = '1234567890';
List<dynamic> _placeList = [];

@override
void initState() {
super.initState();
_controller.addListener(() {
_onChanged();
});
}

_onChanged() {
if (_sessionToken == null) {
setState(() {
_sessionToken = uuid.v4();
});
}
getSuggestion(_controller.text);
}

void getSuggestion(String input) async {


const String PLACES_API_KEY = "your api key";

try{
String baseURL = 'https://maps.googleapis.com/maps/api/place/autocomplete/json';
String request = '$baseURL?input=$input&key=$PLACES_API_KEY&sessiontoken=$_sessionToken';
var response = await http.get(Uri.parse(request));
var data = json.decode(response.body);
if (kDebugMode) {
print('mydata');
print(data);
}
if (response.statusCode == 200) {
setState(() {
_placeList = json.decode(response.body)['predictions'];
});
} else {
throw Exception('Failed to load predictions');
}
}catch(e){
print(e);
}

}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 0,
title: const Text('Search places Api' ,),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Align(
alignment: Alignment.topCenter,
child: TextField(
controller: _controller,
decoration: InputDecoration(
hintText: "Search your location here",
focusColor: Colors.white,
floatingLabelBehavior: FloatingLabelBehavior.never,
prefixIcon: const Icon(Icons.map),
suffixIcon: IconButton(
icon: const Icon(Icons.cancel), onPressed: () {
_controller.clear() ;
},
),
),
),
),
Expanded(
child: ListView.builder(
physics: NeverScrollableScrollPhysics(),
shrinkWrap: true,
itemCount: _placeList.length,
itemBuilder: (context, index) {
return GestureDetector(
onTap: () async {

},
child: ListTile(
title: Text(_placeList[index]["description"]),
),
);
},
),
)
],
),
);
}
}

To understand more about sessions Tokens in detail and why we used it

Thank you, i hope you guys have learned something good.

If this blog helped do like and share.

--

--

Axiftaj
Axiftaj

Written by Axiftaj

Hello, this is Asif Taj a tech enthusiasts providing the quality services for the Android and iOS apps development, UI/UX Research and Designs, and Video ads.