微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

应用状态提升时 TextField 不更新

如何解决应用状态提升时 TextField 不更新

我正在按照 Mitch Tabian 的关于 Jetpack Compose 的 youtube 教程构建一个简单的应用程序。 在 State Hoisting 视频中,他将搜索 TextField 的代码提取一个单独的 Composable 中。当我这样做时,我的 textField 不会更新值,而且我找不到我做错了什么。

SearchAppBar 可组合

@Composable
fun SearchAppBar(
  query: String,onQueryChanged: (String) -> Unit,onExecuteSearch: () -> Unit,selectedCategory: FoodCategory?,onSelectedCategoryChanged: (String) -> Unit
) {
  Surface(
    modifier = Modifier
      .fillMaxWidth(),color = Color.White,elevation = 4.dp
  ) {
    Column {
      Row(modifier = Modifier.fillMaxWidth()) {
        val focusManager = LocalFocusManager.current
        OutlinedTextField(
          value = query,onValueChange = { newValue -> onQueryChanged(newValue) },modifier = Modifier
            .background(color = MaterialTheme.colors.surface)
            .fillMaxWidth()
            .padding(8.dp),label = {
            Text(text = "Search")
          },...

片段

class RecipeListFragment : Fragment() {
  private val viewmodel: RecipeListviewmodel by viewmodels()

  override fun onCreateView(inflater: LayoutInflater,container: ViewGroup?,savedInstanceState: Bundle?): View {
    return ComposeView(requireContext()).apply {
      setContent {
        val recipes = viewmodel.recipes.value
        val query = viewmodel.query.value
        val selectedCategory = viewmodel.selectedCategory.value
        Column {
          SearchAppBar(
            query = query,onQueryChanged = { viewmodel.onQueryChanged(query) },onExecuteSearch = { viewmodel::newSearch },selectedCategory = selectedCategory,onSelectedCategoryChanged = { viewmodel::onSelectedCategoryChanged })
          LazyColumn {
            itemsIndexed(items = recipes) { index,recipe ->
              RecipeCard(recipe = recipe,onClick = { })
            }
          }
        }
      }
    }
  }
}

视图模型

class RecipeListviewmodel @Inject constructor(private val repository: RecipeRepository,@Named("auth_token") private val token: String) : viewmodel() {
  val recipes: MutableState<List<Recipe>> = mutableStateOf(listof())
  val query = mutableStateOf("")
  val selectedCategory: MutableState<FoodCategory?> = mutableStateOf(null)

  init {
    newSearch()
  }

  fun onQueryChanged(query: String) {
    this.query.value = query
  }

  fun newSearch() {
    viewmodelScope.launch {
      recipes.value = repository.search(token = token,page = 1,query = query.value)
    }
  }

  fun onSelectedCategoryChanged(category: String) {
    val newCategory = getFoodCategory(category)
    selectedCategory.value = newCategory
    onQueryChanged(category)
  }
}

解决方法

以下不再是观察到的状态。

val recipes = viewModel.recipes.value
val query = viewModel.query.value
val selectedCategory = viewModel.selectedCategory.value

延迟 .value 调用或使用 var by viewModel.recipes 或使用重组 val (recipes,_) = viewModel.recipes

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。