Search code examples
androidkotlinandroid-jetpack-composeandroid-jetpack-navigationandroid-jetpack-compose-text

Keep text in BasicTextField on back navigation


I have a BasicTextField in my jetpack compose function. When i click(user has input some text into the textfield by now) on a button to navigate to another composable in my NavHost, and from that new view click on back to the composable which i came from which has the textfield, the textfield is empty. I want to keep the text that the user typed in before navigating, but I can't figure it out how. Have looked here but found no answer.

Suggestions?

Here is my code:

@Composable
fun SearchBar(
    modifier: Modifier = Modifier,
    onSearch: (String) -> Unit = {}
) {
    var text by remember {
        mutableStateOf("")
    }

    Box(modifier = modifier) {
        BasicTextField(
            value = text,
            onValueChange = {
                text = it
                onSearch(it)
            },
            maxLines = 1,
            singleLine = true,
            textStyle = TextStyle(color = Color.Black),
            modifier = Modifier
                .fillMaxWidth()
                .shadow(5.dp, CircleShape)
                .background(Color.White, CircleShape)
        )
    }
}

Solution

  • remember saves the value over recomposition (i.e., when your state changes, your composable automatically recomposes with the new state).

    As per the Restore UI State guide, you can replace remember with rememberSaveable to save your state across:

    • Configuration changes
    • Process death and recreation
    • Your composable being put on the NavHost back stack

    As well as any other case where your SearchBar could be removed from composition and then re-added (such as if you were using in Accompanist's Pager or in a LazyColumn or LazyRow).

    var text by rememberSaveable {
        mutableStateOf("")
    }