android 在状态为集合的ViewModel中更新状态

cclgggtu  于 2023-04-10  发布在  Android
关注(0)|答案(1)|浏览(155)

我有一个ViewModel和屏幕,它创建了一个问题列表,并输入答案

@HiltViewModel
class QuestionnaireViewModel @Inject constructor (
    private val _questionRepository: QuestionRepository
): ViewModel() {

    data class AnswerState(
        val question: String,
        var answer: String
    )

    val questions: List<Questions> = _questionRepository.getQuestions("pole1")
    val questionAnswers = questions.map { q -> AnswerState(q.qText, "") }

    private val _viewState = MutableStateFlow<List<AnswerState>>(questionAnswers)
    val viewState = _viewState.asStateFlow() 

    fun updateAnswer(question: String, answer: String) {
        val updatedAnswerState = _viewState.value.toMutableList()
        updatedAnswerState .filter { as -> as.question == question }.get(0).answer = answer
        _viewState.value = updatedAnswerState
    }

然后在我的屏幕上

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun QuestionnaireScreen() {

    val viewModel: QuestionnaireViewModel = hiltViewModel()
    val state by viewModel.viewState.collectAsState()

    Column(modifier = Modifier) {
        
        Text(...Some elements)
   
        Questionnaire(
            state = state,
            onAnswerTextChange = viewModel::updateAnswer,
        )
    }
}

@Composable
private fun Questionnaire(
    modifier: Modifier = Modifier,
    state: List<QuestionnaireViewModel.AnswerState>,
    onAnswerTextChange: (String) -> Unit = {},
) {
    Column (
        modifier = Modifier.padding(15.dp),
        verticalArrangement = Arrangement.spacedBy(10.dp)
    ) {
        state.forEach { questionAnswer ->
            QuestionCard(
                answerState = questionAnswer,
                onAnswerTextChange = onAnswerTextChange
            )
        }
    }
}

@Composable
fun QuestionCard(
    answerState: QuestionnaireViewModel.AnswerState,
    onAnswerTextChange: (String) -> Unit = {}
) {
    Column (
        modifier = Modifier.fillMaxWidth()
    ) {
        Text (
            text = answerState.question
        )
        
        TextField(
            value = answerState.answer,
            onValueChange = onAnswerTextChange
        )
    }
}

那么我如何从我的文本字段onValueChange中提供两个参数,一个是问题文本,用于在我的更新方法中定位正确的状态片段,然后是实际值,用于更新状态值?

hmmo2u0o

hmmo2u0o1#

你能不能把lambda改成两个字符串,像这样?

@Composable
private fun Questionnaire(
  modifier: Modifier = Modifier,
  state: List<QuestionnaireViewModel.AnswerState>,
  onAnswerTextChange: (String, String) -> Unit = {},
) {
  Column (
    modifier = Modifier.padding(15.dp),
    verticalArrangement = Arrangement.spacedBy(10.dp)
  ) {
    state.forEach { questionAnswer ->
      QuestionCard(
        answerState = questionAnswer,
        onAnswerTextChange = { newAnswer -> 
          onAnswerTextChange.invoke(questionAnswer.question, newAnswer)
        }
      )
    }
  }
}

相关问题