I'm using Flutter for the first time in order to build a mobile application and I found no way to implement autocomplete google places in a textEdit component. I aim to obtain a kind of list view while the user is typing the location, as we can do in Android/iOS native implementation and react/ionic.
What I did obtain is a TextEdit component that searches possible locations and take the first one at the end. Here a snippet of my code
class HomeFragmentState extends State<HomeFragment>{
GoogleMapController mapController;
String searchAddr;
List<Marker> markersList = [];
Marker finalMarker;
LatLng _center = LatLng(45.4654219,9.1859243); // default location
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: <Widget>[
GoogleMap(
onMapCreated: onMapCreated,
initialCameraPosition: CameraPosition(
target: _center,
zoom: 11.0,
),
markers: Set.from(markersList),
),
Positioned(
top: 10.0,
right: 15.0,
left: 15.0,
child: Container(
height: 50.0,
width: double.infinity,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10.0),
color: Colors.white
),
child: Column(
children: <Widget>[
TextField(
decoration: InputDecoration(
hintText: 'Enter the place',
border: InputBorder.none,
contentPadding: EdgeInsets.only(left: 15.0,top:15.0),
suffixIcon: IconButton(
icon: Icon(Icons.search),
onPressed: searchAndNavigate,
iconSize: 30.0,
)
),
onChanged: (val) {
setState(() {
searchAddr = val;
});
},
onEditingComplete: searchAndNavigate,
),
],
)
),
),
],
),
);
}
void searchAndNavigate(){
Geolocator().placemarkFromAddress(searchAddr).then((result) => {navigateTo(result:result)});
}
navigateTo({result, init: false}){
var zoom = 11.0;
var target;
if(init){
zoom = 12.0; //difference between searching and initializing
target = LatLng(result.latitude, result.longitude);
} else {
target = LatLng(result[0].position.latitude,result[0].position.longitude);
}
mapController.animateCamera(CameraUpdate.newCameraPosition(CameraPosition(
target:target,
zoom: zoom
)));
}
void onMapCreated(controller){
setState(() {
mapController = controller;
Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.high).then((position) => {
navigateTo(result: position,init: true)
});
});
}
}
As we can see from Geolocator we can retrieve some location based on the address we're typing (hence we can take the results from there) but I didn't find a smart way to implement the part of textedit suggestions