I'm working on a settings screen and a common occu...
# compose
c
I'm working on a settings screen and a common occurance I run into is: 1. Show Dialog with a TextField with current string of SettingA 2. Allow user to edit TextField, but don't actually modify SettingA until the save button is hit I'm currently doing this by essentially having
Copy code
@Composable
fun MySettingDialog(visible: Boolean, seedValue: String, saveEvent: () -> Unit){
var tempValue by remember { mutableStateOf(seedValue) }
if (visible){
    //DialogWithTextField...
    // use tempValue in textField, and onTextUpdate, update tempValue
  }
}
this works fine the first time... but messes up every subsequent time because if the user types something in... it will be remembered, and then when you comes back to the dialog it will have the only remembered value even though the user didn't hit save. It seems like an easy way to do this is for the seedValue to replace tempValue in a LaunchedEffect, but maybe kinda seems hacky. Am I missing something simple here?
Essentially, my solution seems to be
Copy code
@Composable
fun MySettingDialog(visible: Boolean, seedValue: String, saveEvent: () -> Unit){
var tempValue by remember { mutableStateOf("") }

LaunchedEffect(visible) {
  if (visible) tempValue = seedValue
}

if (visible){
    //DialogWithTextField...
    // use tempValue in textField, and onTextUpdate, update tempValue
  }
}
a
Move
visible
out of the composable.
f
your issue is that you have multiple sources of truth. The dialog has its own copy of the value, when you would be better off making your dialog stateless and instead accepting a value and an
onValueUpdated
lambda. Also, the `visible `flag should not be part of the dialog, you should conditionally show or hide the dialog, instead of the dialog receiving a
isVisible
flag
c
@Albert Chang hm. could it be that easy. i think youre onto something though. 😅
@Francesc yeah I don't like the multiple sources... but it seems like I kind of need multiple sources here... no? Like. I need the actual value of the setting, and then the "temp" value of the setting.
a
It's that easy. It will also work if you put
var tempValue by remember { mutableStateOf("") }
inside the if clause, but as a rule of thumb a composable function should always emit something and if you want to show something conditionally you should use an if clause on the call site of it.
c
cool. im circling back to this tomorrow so i will see what I come up with.
f
@Colton Idle let us know if you solved your problem. I had the same issue here but I can't find a properly solution.
c
finally came back to this. lol. ended up doing something like this
Copy code
if (showModal){
    var tempValue by remember { mutableStateOf("") }
    LaunchedEffect(Unit) { tempValue = appStateHolder.settingX.first() }

    SettingXDialog(
      closeEvent = dismiss,
      settingXChangeEvent = settingxChangeEvent,
      settingX = tempValue,
      textChange = { tempValue = it })
  }