I've a list of QA(String,String) where each list item represents 2 TextFields in Lazycolumn, I tried several things but my TextFields value is not updating.
I tried mutableStateListOf() , mutableStateOf() ,
I'm passing the QA(String) value to the TextField and updating the value by catching event in viewModel.
LazyColumn(
modifier = Modifier
.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally
) {
itemsIndexed(
uiState.questionAnswers
) { index, item ->
QuestionAnswerCard(
modifier = Modifier.padding(horizontal = 16.dp, vertical = 16.dp),
question =item.questing,
ans = item.answer,
onQuestionValueChange = { value ->
viewModel.onEvent(
CreateFlashCardScreenEvents.OnChangeQuestion(
value,
index
)
)
},
onAnswerValueChange = {
viewModel.onEvent(CreateFlashCardScreenEvents.OnChangeAnswer(it, index))
}
)
}
}
@Composable
fun QuestionAnswerCard(
modifier: Modifier = Modifier,
question: String,
ans: String,
onQuestionValueChange: (String) -> Unit,
onAnswerValueChange: (String) -> Unit
) {
Card(
modifier = modifier
.fillMaxWidth(),
shape = RoundedCornerShape(12.dp),
elevation = 6.dp
) {
Column(modifier = Modifier.fillMaxWidth()) {
TextField(
modifier = Modifier.fillMaxWidth(),
value = question,
onValueChange = onQuestionValueChange
)
Spacer(modifier = Modifier.height(12.dp))
TextField(
modifier = Modifier.fillMaxWidth(),
value = ans,
onValueChange = onAnswerValueChange
)
}
}
}
class CreateFlashCardsViewModel : ViewModel() {
var createFlashCardUiState by mutableStateOf(CreateFlashCardUiState())
private set
var stateList = mutableStateListOf<QuestionAnswer>()
init {
createFlashCardUiState = createFlashCardUiState.copy(
questionAnswers = createInitialEmptyQAList()
)
stateList.addAll(createInitialEmptyQAList())
}
private fun addNewQAinList() {
val qAList = createFlashCardUiState.questionAnswers + QuestionAnswer(
createFlashCardUiState.questionAnswers.size.toString(),
""
)
createFlashCardUiState = createFlashCardUiState.copy(questionAnswers = qAList)
stateList = stateList.apply {
add(QuestionAnswer())
}
}
private fun createInitialEmptyQAList(): MutableList<QuestionAnswer> {
return mutableListOf(
QuestionAnswer(
questing = "Test Q",
answer = "Test A"
),
QuestionAnswer(
questing = "Test !",
answer = "Test !"
)
)
}
/*In ViewModel*/
fun onEvent(event: CreateFlashCardScreenEvents) {
when (event) {
is CreateFlashCardScreenEvents.OnChangeQuestion -> {
createFlashCardUiState = createFlashCardUiState.copy(
questionAnswers = createFlashCardUiState.questionAnswers.apply {
get(event.index).questing = event.value
}
)
/*tried different state */
stateList.get(event.index).questing = event.value
}