Home > Back-end >  How to use the return of a lambda to update a state of a composable
How to use the return of a lambda to update a state of a composable

Time:09-17

I have a composable function with a textfield and a button

@Composable
private fun ButtonsColumn(
    modifier: Modifier = Modifier,
    // enum class DataEntryInputState
    dataEntryInputState: DataEntryInputState = DataEntryInputState.Default,
    onClickParam: () -> Unit
) {
    // enum class ButtonType that change content of the button
    var buttonState by remember { mutableStateOf(ButtonType.Text) }
    Column(modifier = modifier) {
        DataEntryInputLarge(
            ...
            // custom composable
            ...
        )
        ButtonPrimary(
            modifier = Modifier
                .fillMaxWidth()
                .clickable {
                    buttonState = ButtonType.Loading
                },
            text = "Login",
            enabled = textFieldState,
            type = buttonState,
            onClick = onClickParam
        )
    }
}

I want to update buttonState when onClick finish, something like:

onClickParam: () -> Boolean
...
        onClick = {
            if(!onClickParam){
                buttonState = DataEntryInputState.Default
            }
        }

It means that when the lambda function finishes if it's false update the content of the button according to what I already have. I don't sure if it's possible or if it's another way to do that.

CodePudding user response:

Just accept something for the lambda, for example, this updates a boolean value based on the current value

fun CustomComposable(
onClick: (Boolean) -> Boolean
){
var myBoolean by mutableStateOf (false)
myBoolean = onClick(myBoolean)
}

Now, the onClick parameter can be implemented something like this:

{ receivedBoolean -> //You can also use 'it' keyword to access this
return !receivedBoolean //Just return the complimentary boolean 
}

When implemented like this, your Composable is passing in a Boolean to the onClick which is returning the complimentary boolean, and hence, when this onClick is complete, thr value of myBoolean within the Composable will be flipped. This is achieved by simply adding a getter, by adding a value in the parenthesis of onClick, and a setter, implemented by returning a Boolean instead of Unit. This is just an example. Implement it the way you want. The method will remain the same.

CodePudding user response:

The recommended way is to create a mutable state in your parent composable like

var dataEntryState by remember { mutableStateOf(DataEntryInputState.Default) }

and call ButtonsColumn composable from it's paranet like

ButtonsColumn(modifier, dataEntryState) {
   // Update state after finishing lamba
   dataEntryState = DataEntryInputState.Default
}
  • Related