How to deal with textfield and viewmodel? should I...
# compose
p
How to deal with textfield and viewmodel? should I have the value of the textfield inside the uistate variable of the viewmodel? or should I have it in a mutable state var in the viewmodel? I'm attaching some samples in the thread...
ViewModel Approach 1:
Copy code
data class MainScreenUiState(
    val loading: Boolean = false,
    val textFieldValue: String
)

private val _uiState = MutableStateFlow<MainScreenUiState>(MainScreenUiState(loading = true))
    val uiState: StateFlow<MainScreenUiState> = _uiState

fun updateTextFieldValue(value: String) {
    _uiState.value = _uiState.value.copy(textFieldValue = value)
}
Copy code
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
TextField(
    value = uiState.textFieldValue ,
    onValueChange = { viewModel.updateTextFieldValue(it) }
)
ViewModel Approach 2:
Copy code
var textFieldValue by mutableStateOf("")

fun updateTextFieldValue(value: String) {
    textFieldValue = value
}
Copy code
TextField(
    value = viewModel.textFieldValue ,
    onValueChange = { textFieldValue.updateTextFieldValue(it) }
)
p
so I must avoid using uistate
and instead of that I must use mutablestateof variable inside the viewmodel, one for each textfield
do I understood it correctly?
z
I don’t think the stable material release supports it yet, but once it does - yea definitely
s
Or better yet, don't use material3 😅
🌶️ 1
p
if we don't use material3, what should we use?
and why you recommend to not using it?
s
Just joking, use whatever fits your needs. We mostly don't use material because our design system doesn't match material, that's all 🤷