Hey, I want you to build to google places autocomplete on jetpack compose using the MVVM…
- User
Hey, I want you to build to google places autocomplete on jetpack compose using the MVVM model
So the user will type the place in a textfield and the list of places with postalCode will display in a lazyColumn with the user able to select from the lazyColumn a place
- Assistant
Sure, I can help you with that! To build a Google Places autocomplete feature in Jetpack Compose using the MVVM architecture, you will need to:
- Create a ViewModel that will hold the list of places returned from the Google Places API and handle the API request.
- Build a Composable that will display the search bar and the list of places returned from the API.
- Create a Repository that will handle the API request and parse the response.
Here's an example implementation that you can use as a starting point:
ViewModel:
kotlinclass PlacesViewModel(private val repository: PlacesRepository) : ViewModel() { private val _places = MutableLiveData<List<Place>>() val places: LiveData<List<Place>> = _places fun searchPlaces(query: String) { viewModelScope.launch { val placesList = repository.searchPlaces(query) _places.postValue(placesList) } } }Repository:
kotlinclass PlacesRepository { private val placesApi = PlacesApi.create() suspend fun searchPlaces(query: String): List<Place> { val response = placesApi.searchPlaces(query) if (response.isSuccessful) { return response.body()?.predictions?.map { prediction -> Place(prediction.placeId, prediction.description, prediction.structuredFormatting?.mainText, prediction.structuredFormatting?.secondaryText, prediction.terms?.getOrNull(0)?.value, prediction.terms?.getOrNull(1)?.value) } ?: emptyList() } else { throw IOException("Error searching places") } } }Composable:
scss@Composable fun PlacesAutocomplete( viewModel: PlacesViewModel, onPlaceSelected: (Place) -> Unit ) { var query by remember { mutableStateOf("") } val places by viewModel.places.observeAsState() Column { TextField( value = query, onValueChange = { query = it }, label = { Text("Search for a place") }, modifier = Modifier .fillMaxWidth() .padding(16.dp) ) LazyColumn { items(places ?: emptyList()) { place -> PlaceItem(place, onPlaceSelected) } } } LaunchedEffect(query) { viewModel.searchPlaces(query) } } @Composable fun PlaceItem(place: Place, onPlaceSelected: (Place) -> Unit) { Box( modifier = Modifier .fillMaxWidth() .clickable { onPlaceSelected(place) } .padding(16.dp) ) { Column { Text(place.description, fontWeight = FontWeight.Bold) Text("${place.primaryText}, ${place.secondaryText}") Text(place.postalCode ?: "", style = MaterialTheme.typography.caption) } } }In this implementation, the
PlacesAutocompletecomposable displays a search bar and aLazyColumnofPlaceItemcomposables that display each place returned from the API. ThePlaceItemcomposable is clickable and calls theonPlaceSelectedcallback when clicked.When the user types in the search bar, the
LaunchedEffectblock in thePlacesAutocompletecomposable calls thesearchPlacesfunction in the ViewModel, which in turn calls thesearchPlacesfunction in the Repository to fetch the list of places from the Google Places API.Note that this implementation uses the
Retrofitlibrary to make the API request and theGsonlibrary to parse the JSON response. You will need to add these libraries to your project and configure them accordingly. Additionally, you will need to obtain a Google Places API key and set it up in your project. - User
PlacesAutocomplete needs to be inside a bottomSheet
- Assistant
Sure! To place the
PlacesAutocompletecomposable inside aBottomSheet, you can wrap it inside aModalBottomSheetLayoutcomposable. Here's an updated implementation:scss@Composable fun PlacesAutocompleteBottomSheet( viewModel: PlacesViewModel, onPlaceSelected: (Place) -> Unit, bottomSheetState: ModalBottomSheetState, ) { var query by remember { mutableStateOf("") } val places by viewModel.places.observeAsState() ModalBottomSheetLayout( sheetState = bottomSheetState, sheetContent = { Column { TextField( value = query, onValueChange = { query = it }, label = { Text("Search for a place") }, modifier = Modifier .fillMaxWidth() .padding(16.dp) ) LazyColumn { items(places ?: emptyList()) { place -> PlaceItem(place, onPlaceSelected) } } } } ) { Box( modifier = Modifier .fillMaxSize() .clickable { bottomSheetState.show() } ) { Text("Open bottom sheet") } } LaunchedEffect(query) { viewModel.searchPlaces(query) } }In this updated implementation, the
PlacesAutocompleteBottomSheetcomposable takes abottomSheetStateparameter, which is used to control the visibility of the bottom sheet.The
ModalBottomSheetLayoutcomposable is used to create the bottom sheet. The content of the bottom sheet is the same as before: a search bar and aLazyColumnofPlaceItemcomposables. The entire content of the bottom sheet is passed as thesheetContentparameter to theModalBottomSheetLayoutcomposable.The
Boxcomposable is used as a placeholder for the content that will trigger the bottom sheet to open. In this example, it's just a simple text that says "Open bottom sheet". ThebottomSheetState.show()function is called when theBoxcomposable is clicked, which will show the bottom sheet.Note that you will need to pass a
ModalBottomSheetStateobject to thebottomSheetStateparameter in thePlacesAutocompleteBottomSheetcomposable. You can create aModalBottomSheetStateobject by calling therememberModalBottomSheetStatefunction. - User
Please fix the PlacsRepository
- Assistant
Sure, here's an updated implementation of the
PlacesRepositorythat uses thePlacesApito fetch the places:kotlinclass PlacesRepository(private val placesApi: PlacesApi) { suspend fun searchPlaces(query: String): List<Place> { val response = placesApi.searchPlaces(query) return response.results.map { result -> Place( name = result.name, address = result.formatted_address, latitude = result.geometry.location.lat, longitude = result.geometry.location.lng, postalCode = result.address_components .firstOrNull { it.types.contains("postal_code") } ?.short_name ) } } }In this implementation, the
PlacesRepositorytakes an instance of thePlacesApiin its constructor, which will be used to fetch the places.The
searchPlacesfunction calls thesearchPlacesfunction on thePlacesApiwith thequeryparameter. It then maps the response to a list ofPlaceobjects, where eachPlaceobject is constructed using the relevant fields from the response. ThepostalCodefield is extracted from the first address component that has a type of "postal_code".Note that this implementation assumes that the
PlacesApireturns a response that has aresultsfield, which contains a list of search results. If your implementation of thePlacesApireturns a different response structure, you may need to adjust this implementation accordingly. - User
can we make PlaceItem into a card
- Assistant
Yes, you can wrap the contents of the
PlaceItemcomposable inside aCardcomposable to give it a card-like appearance. Here's an updated implementation of thePlaceItemcomposable that uses aCard:scss@Composable fun PlaceItem(place: Place, onPlaceSelected: (Place) -> Unit) { Card( modifier = Modifier .fillMaxWidth() .clickable { onPlaceSelected(place) } .padding(16.dp), elevation = 4.dp ) { Column( modifier = Modifier .fillMaxWidth() .padding(16.dp) ) { Text( text = place.name, fontWeight = FontWeight.Bold, fontSize = 18.sp ) Spacer(modifier = Modifier.height(8.dp)) Text( text = place.address ?: "", fontSize = 16.sp, color = MaterialTheme.colors.onSurface.copy(alpha = 0.6f) ) Spacer(modifier = Modifier.height(8.dp)) Text( text = place.postalCode ?: "", fontSize = 14.sp, color = MaterialTheme.colors.onSurface.copy(alpha = 0.6f) ) } } }In this updated implementation, the contents of the
PlaceItemcomposable are wrapped inside aCardcomposable. TheCardhas amodifierthat specifies a few properties: it should fill the maximum available width, have a clickable behavior, and have some padding. Theelevationproperty is also set to give the card a raised appearance.Inside the
Card, the contents of thePlaceItemcomposable are the same as before: aColumnthat contains the name, address, and postal code of the place. TheColumnhas amodifierthat specifies that it should fill the maximum available width and have some padding.Note that you can adjust the appearance of the
Cardby changing its properties, such as thebackgroundColor,shape, orborder. You can also wrap other composables inside aCardto give them a card-like appearance.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.