https://kotlinlang.org logo
b

Brian Norman

05/01/2020, 3:43 PM
Hey everyone, I'm new to Compose so pardon the potentially stupid question... I've got a Column of Composables that I'd like to filter based on a search bar, but I'm wondering how I can get the search bar's text lifted to its parent composable? I'm running into issues where if I pass a
@Model
object into the Search Bar composable from the parent then it'll get reset every time I type (I'm guessing this is because the parent re-renders causing the Search Bar re-renders)... If anyone's done this and could share how they've done it or point me in the right direction that would be super helpful! Thanks 🙂
k

Kazemihabib1996

05/01/2020, 3:50 PM
Can you share you're current code?
👍 1
b

Brian Norman

05/01/2020, 3:55 PM
Copy code
@Model
class SearchState(
    var textField : TextFieldValue = TextFieldValue()
)

@Composable
fun SearchBar(searchState: SearchState) {
    Surface(color = Color.LightGray, modifier = Modifier.padding(16.dp), shape = RoundedCornerShape(5.dp)) {
        TextField(
            value = searchState.textField,
            modifier = Modifier.padding(16.dp) + Modifier.fillMaxWidth(),
            imeAction = ImeAction.Search,
            onValueChange = { searchState.textField = it }
        )
    }
}

@Composable
private fun FeedContent(
    modifier: Modifier,
    entriesList: List<Entry>,
    searchState: SearchState = SearchState()
) {
    Stack(modifier = modifier.fillMaxSize()) {
        VerticalScroller {
            Column {
                SearchBar(searchState)
                for (entry in entriesList) {
                    if (entry.restaurant.toLowerCase().contains(searchState.textField.text.toLowerCase())) {
                        Clickable(onClick = { navigateTo(Screen.Entry(entry)) }) {
                            FeedCard(entry = entry)
                        }
                    }
                }
            }
        }
    }
}
Oh you know what I solved it
k

Kazemihabib1996

05/01/2020, 4:00 PM
with
remeber {SearchState()}
?
b

Brian Norman

05/01/2020, 4:00 PM
Yes haha
I think I need to find some documentation on
remember
to fully wrap my head around how that works, but thank you!
k

Kazemihabib1996

05/01/2020, 4:02 PM
As you are using
searchState.textField
inside FeedContent every time it changes
FeedContent
is recomposed and you have a new
SearchState()
remeber
is kind of like C languages static variables(First I read about
remeber
I thought about it like this)
b

Brian Norman

05/01/2020, 4:05 PM
Oh yeah that clears it up actually thanks a bunch 🙏
👍 1
2 Views