【问题标题】:Jetpack Compose rememberSwipeableState recycling issueJetpack Compose rememberSwipeableState 回收问题
【发布时间】:2022-10-23 15:51:07
【问题描述】:

我有一个LazyColumn,它从列表数据结构中生成项目,每个项目都有一个swipeable state。一旦从列表(数据结构)中删除项目,它也会反映在 UI 中,启动重组并更新 LazyColumn - 不显示已删除的项目 - 正确。

问题是,LazyColumn 项的所有滑动状态变量都和删除前一样,例如,如果列表为redgreenblue绿色被删除,滑动状态为绿色在列表中排名第二的现在是blue 的滑动状态,现在在列表中排名第二。所有项目都向左移动,但状态保持不变。

这是代码:


var dailyItems= viewModel.getItems().observeAsState(initial = emptyList())

LazyColumn(...) {
   items(dailyItems) { item ->
                SomeItem(
                    item = item,
                )
            }
}

SomeItem 中有一个 swipeable 子组件

@Composable
private fun SomeItem(
  item: Item
) {

    val swipeState = rememberSwipeableState(
        initialValue = ItemState.HIDDEN,
        confirmStateChange = {
            onActionsReveal(item.id) // Note the use if item instance
            true
        }
    )



   Box(
        Modifier.swipeable(
            state = swipeState,
            anchors = anchors,
            orientation = Orientation.Horizontal,
            enabled = true,
            reverseDirection = isRtl
        )
    ) {
      ...
    }
}

 val swipeState = rememberSwipeableState()

val swipeStateSomeItem 重新组合时重新创建,我看到分配给它的新内存地址,我还看到item.id 不同。

但是confirmStateChange 没有被覆盖,或者swipeState 的先前实例在未来的调用中以某种方式被引用 - 当confirmStateChange 被调用时 - 它总是引用初始的item.id

【问题讨论】:

    标签: android android-jetpack-compose


    【解决方案1】:

    通过将rememberUpdatedState 应用于 item.id 解决了问题

    
    val id by rememberUpdatedState(item.id)
    
    val swipeState = rememberSwipeableState(
            initialValue = ItemState.HIDDEN,
            confirmStateChange = {
                onActionsReveal(id)
                true
            }
        )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-07
      • 2021-10-13
      • 2021-06-29
      • 2021-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多