0
votes

I use the following code to show a edit box dialog with initial value on which a use can input a new description and save it.

I think that the initial value "Hello" will be shown on TextField when I click the "Edit Description" button, but in fact, none is shown on TextField.

What's wrong with my code?

@Composable
fun ScreenDetail(
) {

    var editDialog by remember { mutableStateOf(false) }
    var description by remember {mutableStateOf("") }

     editDialog(
         isShow = editDialog,
         onDismiss = { editDialog =false },
         onConfirm ={ ... },
         editFieldContent=description
     )


    Button(
        modifier = Modifier,
        onClick = {
            description = "Hello"
            editDialog = true
        }
    ) {
        Text("Edit Description")
    }
}



@Composable
fun editDialog(
    isShow: Boolean,
    onDismiss: () -> Unit,
    onConfirm: (String) -> Unit,
    saveTitle: String = "Save",
    cancelTitle:String = "Cancel",
    dialogTitle:String ="Edit",
    editFieldTitle:String ="Input description",
    editFieldContent:String ="",
) {
    var mText by remember { mutableStateOf(editFieldContent) }

    if (isShow) {
        AlertDialog(

            confirmButton = {
                TextButton(onClick = { onConfirm(mText) })
                { Text(text = saveTitle) }
            },

            dismissButton = {
                TextButton(onClick = onDismiss)
                { Text(text = cancelTitle) }
            },

            onDismissRequest = onDismiss,
            title = { Text(text = dialogTitle) },

            text = {
                Column() {
                    Text(text = editFieldTitle)
                    TextField(
                        value = mText,
                        onValueChange = { mText = it }
                    )
                }
            }
        )
    }
}
1

1 Answers

0
votes
var mText by remember { mutableStateOf(editFieldContent) }

it doesn't get updated when editFieldContent changes because remember{} stores value on composition or when keys change.

Then you change mText via delegation or using mText.value = newValue if you don't use by keyword.

If you set a key, block inside remember will be recalculated when editFieldContent parameter of editDialog changes.

var mText by remember(editFieldContent) { mutableStateOf(editFieldContent) }