Problems Implementing Drag Drop In LazyColumn

I am trying to implement drag-and-drop reordering in a LazyColumn in a Compose app. I am using a ViewModel and a Room database to store the values. While I have successfully implemented the drag-and-drop feature, the items in the list are being swapped arbitrarily, and their positions change unexpectedly after swapping two items. Any help would be appreciated.

Here is the screenshot and the important parts of the code:

enter image description here

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code># Composable
@RequiresApi(Build.VERSION_CODES.O)
@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)
@Composable
fun WorkoutSessionScreen(
navController: NavController,
workoutSessionViewModel: WorkoutSessionViewModel = hiltViewModel(),
workoutId: Int,
) {
val uiSetsState = workoutSessionViewModel.uiSetsState.collectAsState()
Scaffold(
modifier = Modifier
................
}, ) { innerPadding ->
Column(
modifier = Modifier
.padding(innerPadding)
)
{
val enteredIndex = remember { mutableIntStateOf(-1) }
LazyColumn(
modifier = Modifier
.fillMaxSize()
.padding(start = 14.dp, end = 14.dp)
) {
itemsIndexed(items = uiSetsState.value,
key = { index, item ->
item.set.setId!!
}) { index, setItem ->
Row(
modifier = Modifier
.fillMaxWidth()
.wrapContentHeight()
) {
simpleDetailItem(modifier = Modifier
.then(
if (enteredIndex.intValue == index) {
Modifier.background(Color.Cyan)
} else Modifier.background(Color.White)
)
.dragAndDropTarget(
shouldStartDragAndDrop = {
true
},
target = object : DragAndDropTarget {
override fun onDrop(event: DragAndDropEvent): Boolean {
setItem.set.setId?.let {
workoutSessionViewModel.swapDroppedSet(
it
)
}
enteredIndex.intValue = -1
return true
}
override fun onEntered(event: DragAndDropEvent) {
super.onEntered(event)
enteredIndex.intValue = index
}
override fun onExited(event: DragAndDropEvent) {
super.onExited(event)
enteredIndex.intValue = -1
}
}
),
setItem.set,
setDraggedItem = {
workoutSessionViewModel.setDraggedItem(it)
})
}
}
}
}//Column
}//scaffold
}
</code>
<code># Composable @RequiresApi(Build.VERSION_CODES.O) @OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class) @Composable fun WorkoutSessionScreen( navController: NavController, workoutSessionViewModel: WorkoutSessionViewModel = hiltViewModel(), workoutId: Int, ) { val uiSetsState = workoutSessionViewModel.uiSetsState.collectAsState() Scaffold( modifier = Modifier ................ }, ) { innerPadding -> Column( modifier = Modifier .padding(innerPadding) ) { val enteredIndex = remember { mutableIntStateOf(-1) } LazyColumn( modifier = Modifier .fillMaxSize() .padding(start = 14.dp, end = 14.dp) ) { itemsIndexed(items = uiSetsState.value, key = { index, item -> item.set.setId!! }) { index, setItem -> Row( modifier = Modifier .fillMaxWidth() .wrapContentHeight() ) { simpleDetailItem(modifier = Modifier .then( if (enteredIndex.intValue == index) { Modifier.background(Color.Cyan) } else Modifier.background(Color.White) ) .dragAndDropTarget( shouldStartDragAndDrop = { true }, target = object : DragAndDropTarget { override fun onDrop(event: DragAndDropEvent): Boolean { setItem.set.setId?.let { workoutSessionViewModel.swapDroppedSet( it ) } enteredIndex.intValue = -1 return true } override fun onEntered(event: DragAndDropEvent) { super.onEntered(event) enteredIndex.intValue = index } override fun onExited(event: DragAndDropEvent) { super.onExited(event) enteredIndex.intValue = -1 } } ), setItem.set, setDraggedItem = { workoutSessionViewModel.setDraggedItem(it) }) } } } }//Column }//scaffold } </code>
# Composable

@RequiresApi(Build.VERSION_CODES.O)
@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)
@Composable
fun WorkoutSessionScreen(
    navController: NavController,
    workoutSessionViewModel: WorkoutSessionViewModel = hiltViewModel(),
    workoutId: Int,
) {  
    val uiSetsState = workoutSessionViewModel.uiSetsState.collectAsState()

    Scaffold(
        modifier = Modifier           
................

        },    ) { innerPadding ->
        Column(
            modifier = Modifier
                .padding(innerPadding)
        )
        {
            val enteredIndex = remember { mutableIntStateOf(-1) }
            LazyColumn(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(start = 14.dp, end = 14.dp)
            ) {
                itemsIndexed(items = uiSetsState.value,
                    key = { index, item ->
                        item.set.setId!!
                    }) { index, setItem ->
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .wrapContentHeight()
                    ) {
                        simpleDetailItem(modifier = Modifier
                            .then(
                                if (enteredIndex.intValue == index) {
                                    Modifier.background(Color.Cyan)
                                } else Modifier.background(Color.White)
                            )
                            .dragAndDropTarget(
                                shouldStartDragAndDrop = {
                                    true
                                },
                                target = object : DragAndDropTarget {
                                    override fun onDrop(event: DragAndDropEvent): Boolean {
                                        setItem.set.setId?.let {
                                            workoutSessionViewModel.swapDroppedSet(
                                                it
                                            )
                                        }
                                        enteredIndex.intValue = -1
                                        return true
                                    }
                                    override fun onEntered(event: DragAndDropEvent) {
                                        super.onEntered(event)
                                        enteredIndex.intValue = index
                                    }
                                    override fun onExited(event: DragAndDropEvent) {
                                        super.onExited(event)
                                        enteredIndex.intValue = -1
                                    }
                                }
                            ),
                            setItem.set,
                            setDraggedItem = {
                                workoutSessionViewModel.setDraggedItem(it)
                            })
                    }

                }

            }
        }//Column
    }//scaffold
}
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun simpleDetailItem(
modifier: Modifier,
set: Set,
setDraggedItem: (id: Long?) -> Unit
) {
Row(
modifier = modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 16.dp)
.height(80.dp)
.border(width = 2.dp, color = Color.Green)
.dragAndDropSource {
detectTapGestures(
onLongPress = {
startTransfer(
DragAndDropTransferData(
ClipData.newPlainText(
"image Url", "test"
)
)
)
setDraggedItem(set.setId)
},
onTap = {
}
)
},
) {
set.exerciseTitle?.let {
Text(
modifier = Modifier
.padding(horizontal = 8.dp, vertical = 8.dp),
text = it + " - " + set.setId + " - " + set.setOrder
)
}
}
}
</code>
<code> @OptIn(ExperimentalFoundationApi::class) @Composable fun simpleDetailItem( modifier: Modifier, set: Set, setDraggedItem: (id: Long?) -> Unit ) { Row( modifier = modifier .fillMaxWidth() .padding(horizontal = 16.dp, vertical = 16.dp) .height(80.dp) .border(width = 2.dp, color = Color.Green) .dragAndDropSource { detectTapGestures( onLongPress = { startTransfer( DragAndDropTransferData( ClipData.newPlainText( "image Url", "test" ) ) ) setDraggedItem(set.setId) }, onTap = { } ) }, ) { set.exerciseTitle?.let { Text( modifier = Modifier .padding(horizontal = 8.dp, vertical = 8.dp), text = it + " - " + set.setId + " - " + set.setOrder ) } } } </code>


@OptIn(ExperimentalFoundationApi::class)
@Composable
fun simpleDetailItem(
    modifier: Modifier,
    set: Set,
    setDraggedItem: (id: Long?) -> Unit
) {
    Row(
        modifier = modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp, vertical = 16.dp)
            .height(80.dp)
            .border(width = 2.dp, color = Color.Green)
            .dragAndDropSource {
                detectTapGestures(
                    onLongPress = {                   
                        startTransfer(
                            DragAndDropTransferData(
                                ClipData.newPlainText(
                                    "image Url", "test"
                                )
                            )
                        )
                        setDraggedItem(set.setId)
                    },
                    onTap = {                     
                    }
                )
            },

        ) {

        set.exerciseTitle?.let {
            Text(
                modifier = Modifier
                    .padding(horizontal = 8.dp, vertical = 8.dp),
                text = it + " - " + set.setId + " - " + set.setOrder
            )
        }
    }
}

ViewModel

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>
@RequiresApi(Build.VERSION_CODES.O)
@HiltViewModel
class WorkoutSessionViewModel @Inject constructor(
private val setRepository: SetRepository,
private val exerciseRepository: ExerciseRepository,
private val savedStateHandle: SavedStateHandle,
) : ViewModel() {
private var _uiSetsState: StateFlow<List<SetWithMeasurements>> =
setRepository.getSetsOfWorkoutWithMeasurements(savedStateHandle[WORKOUT_ID]!!)
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000),
initialValue = emptyList(),
)
val uiSetsState: StateFlow<List<SetWithMeasurements>> = _uiSetsState
fun swapDroppedSet(droppedSetId: Long) {
CoroutineScope(Dispatchers.IO).launch {
if (draggedSetId != droppedSetId) {
setRepository.swapTwoSets(draggedSetId, droppedSetId)
}
draggedSetId = 0
}
}
fun setDraggedItem(setId: Long?) {
if (setId != null) {
draggedSetId = setId
}
}
</code>
<code> @RequiresApi(Build.VERSION_CODES.O) @HiltViewModel class WorkoutSessionViewModel @Inject constructor( private val setRepository: SetRepository, private val exerciseRepository: ExerciseRepository, private val savedStateHandle: SavedStateHandle, ) : ViewModel() { private var _uiSetsState: StateFlow<List<SetWithMeasurements>> = setRepository.getSetsOfWorkoutWithMeasurements(savedStateHandle[WORKOUT_ID]!!) .stateIn( scope = viewModelScope, started = SharingStarted.WhileSubscribed(5_000), initialValue = emptyList(), ) val uiSetsState: StateFlow<List<SetWithMeasurements>> = _uiSetsState fun swapDroppedSet(droppedSetId: Long) { CoroutineScope(Dispatchers.IO).launch { if (draggedSetId != droppedSetId) { setRepository.swapTwoSets(draggedSetId, droppedSetId) } draggedSetId = 0 } } fun setDraggedItem(setId: Long?) { if (setId != null) { draggedSetId = setId } } </code>

@RequiresApi(Build.VERSION_CODES.O)
@HiltViewModel
class WorkoutSessionViewModel @Inject constructor(
    private val setRepository: SetRepository,
    private val exerciseRepository: ExerciseRepository,
    private val savedStateHandle: SavedStateHandle,
) : ViewModel() {

    private var _uiSetsState: StateFlow<List<SetWithMeasurements>> =
        setRepository.getSetsOfWorkoutWithMeasurements(savedStateHandle[WORKOUT_ID]!!)
            .stateIn(
                scope = viewModelScope,
                started = SharingStarted.WhileSubscribed(5_000),
                initialValue = emptyList(),
            )
    val uiSetsState: StateFlow<List<SetWithMeasurements>> = _uiSetsState

    fun swapDroppedSet(droppedSetId: Long) {
        CoroutineScope(Dispatchers.IO).launch {
            if (draggedSetId != droppedSetId) {
                setRepository.swapTwoSets(draggedSetId, droppedSetId)                
            }
            draggedSetId = 0
        }
    }
    fun setDraggedItem(setId: Long?) {
        if (setId != null) {
            draggedSetId = setId          
        }
    }

Repository

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> suspend fun swapTwoSets(draggedSet: Long, droppedSet: Long) {
val setDragged = setDao.getSetBySetIdWithMeasurements(draggedSet)
val setDropped = setDao.getSetBySetIdWithMeasurements(droppedSet)
if (setDragged != null && setDropped != null) {
val temp = setDragged.set.setOrder
setDragged.set.setOrder = setDropped.set.setOrder
setDropped.set.setOrder = temp
setDao.upsert(setDropped.set)
setDao.upsert(setDragged.set)
}
}
fun getSetsOfWorkoutWithMeasurements(workoutId: Long): Flow<List<SetWithMeasurements>> {
return setDao.getSetsByWorkoutIdWithMeasurements(workoutId).map { sets ->
sets.filter { it.set.exerciseID != null }
.onEach { setsWithMeasure ->
setsWithMeasure.set.exerciseTitle =
exerciseDao.getExerciseById(setsWithMeasure.set.exerciseID)?.title
}
}
}
</code>
<code> suspend fun swapTwoSets(draggedSet: Long, droppedSet: Long) { val setDragged = setDao.getSetBySetIdWithMeasurements(draggedSet) val setDropped = setDao.getSetBySetIdWithMeasurements(droppedSet) if (setDragged != null && setDropped != null) { val temp = setDragged.set.setOrder setDragged.set.setOrder = setDropped.set.setOrder setDropped.set.setOrder = temp setDao.upsert(setDropped.set) setDao.upsert(setDragged.set) } } fun getSetsOfWorkoutWithMeasurements(workoutId: Long): Flow<List<SetWithMeasurements>> { return setDao.getSetsByWorkoutIdWithMeasurements(workoutId).map { sets -> sets.filter { it.set.exerciseID != null } .onEach { setsWithMeasure -> setsWithMeasure.set.exerciseTitle = exerciseDao.getExerciseById(setsWithMeasure.set.exerciseID)?.title } } } </code>
    suspend fun swapTwoSets(draggedSet: Long, droppedSet: Long) {
        val setDragged = setDao.getSetBySetIdWithMeasurements(draggedSet)
        val setDropped = setDao.getSetBySetIdWithMeasurements(droppedSet)

        if (setDragged != null && setDropped != null) {
            val temp = setDragged.set.setOrder
            setDragged.set.setOrder = setDropped.set.setOrder
            setDropped.set.setOrder = temp

            setDao.upsert(setDropped.set)
            setDao.upsert(setDragged.set)
        }
    }

    fun getSetsOfWorkoutWithMeasurements(workoutId: Long): Flow<List<SetWithMeasurements>> {
        return setDao.getSetsByWorkoutIdWithMeasurements(workoutId).map { sets ->
            sets.filter { it.set.exerciseID != null }
                .onEach { setsWithMeasure ->
                    setsWithMeasure.set.exerciseTitle =
                        exerciseDao.getExerciseById(setsWithMeasure.set.exerciseID)?.title             
                }
        }
    }

I have tried adding keys to lazycolumn. I have learned that adding keys prevent problems about item positions and orders but it did not change anything.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật