I'm trying to write an answer to this question, but while testing my code, i discovered a bug that i couldn’t figure out how to fix.
The app is a task manager where you can drag and drop tasks between queues: To Do
, In Progress
, and Done
. Each queue has a list of tasks, and dragging a task moves it from one queue to another.
Here's a minimal example of my code to reproduce the issue:
implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.8.5")
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
App(modifier = Modifier
.padding(innerPadding)
)
}
}
}
}
enum class QueueType(val title: String) {
TodoQueue("To Do"),
InProgressQueue("In Progress"),
DoneQueue("Done")
}
data class Task(
val title: String,
val description: String
)
class MyViewModel: ViewModel() {
val todoTasks = mutableStateListOf<Task>(
Task("Task 1", "Description 1"),
Task("Task 4", "Description 4"),
)
val inProgressTasks = mutableStateListOf<Task>(
Task("Task 2", "Description 2"),
Task("Task 5", "Description 5"),
)
val doneTasks = mutableStateListOf<Task>(
Task("Task 3", "Description 3"),
)
fun moveTask(
task: Task,
from: QueueType,
to: QueueType
) {
when(from) {
QueueType.TodoQueue -> todoTasks.remove(task)
QueueType.InProgressQueue -> inProgressTasks.remove(task)
QueueType.DoneQueue -> doneTasks.remove(task)
}
when(to) {
QueueType.TodoQueue -> todoTasks.add(task)
QueueType.InProgressQueue -> inProgressTasks.add(task)
QueueType.DoneQueue -> doneTasks.add(task)
}
}
}
data class DraggedData(
val task: Task,
val originQueue: QueueType,
)
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun TaskCard(
task: Task,
queueType: QueueType,
modifier: Modifier = Modifier
) {
Column(
modifier = modifier
.dragAndDropSource {
detectTapGestures(
onLongPress = {
startTransfer(
DragAndDropTransferData(
ClipData.newPlainText("Task", "Task"),
//passe data to be used later when dropping the card
localState = DraggedData(task, queueType)
)
)
}
)
}
.background(
color = Color.LightGray,
shape = RoundedCornerShape(8.dp)
)
.padding(vertical = 4.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
Text(text = task.title)
Text(text = task.description)
}
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun QueueTask(
queueType: QueueType,
tasks: List<Task>,
modifier: Modifier = Modifier,
onTaskDrop: (Task, QueueType) -> Unit
) {
val dropTarget = remember {
object : DragAndDropTarget {
override fun onDrop(dragStartEvent: DragAndDropEvent): Boolean {
val dropEvent = dragStartEvent.toAndroidDragEvent()
// get the dragged data from localState passed earlier
val draggedTaskData = dropEvent.localState as? DraggedData
val droppedTask = draggedTaskData?.task
droppedTask?.let { onTaskDrop(it, draggedTaskData.originQueue) }
return true
}
}
}
Column(
modifier = modifier
.dragAndDropTarget (
shouldStartDragAndDrop = { dragStartEvent ->
dragStartEvent.mimeTypes().contains(ClipDescription.MIMETYPE_TEXT_PLAIN)
}, target = dropTarget
)
.border(
width = 1.dp,
color = Color.Black,
shape = RoundedCornerShape(8.dp)
)
.fillMaxHeight(),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(text = queueType.title)
Spacer(modifier = Modifier.height(4.dp))
tasks.forEach { task ->
TaskCard(
task = task,
queueType = queueType,
modifier = Modifier
.padding(vertical = 4.dp)
)
}
}
}
@Composable
fun App(
modifier: Modifier = Modifier,
viewModel: MyViewModel = viewModel()
) {
val todoTasks = viewModel.todoTasks
val inProgressTasks = viewModel.inProgressTasks
val doneTasks = viewModel.doneTasks
Row(
modifier = modifier,
horizontalArrangement = Arrangement.spacedBy(10.dp)
) {
QueueTask(
queueType = QueueType.TodoQueue,
tasks = todoTasks,
modifier = Modifier.weight(1f),
onTaskDrop = { task, fromQueueType ->
viewModel.moveTask(task, fromQueueType, QueueType.TodoQueue)
}
)
QueueTask(
queueType = QueueType.InProgressQueue,
tasks = inProgressTasks,
modifier = Modifier.weight(1f),
onTaskDrop = { task, fromQueueType ->
viewModel.moveTask(task, fromQueueType, QueueType.InProgressQueue)
}
)
QueueTask(
queueType = QueueType.DoneQueue,
tasks = doneTasks,
modifier = Modifier.weight(1f),
onTaskDrop = { task, fromQueueType ->
viewModel.moveTask(task, fromQueueType, QueueType.DoneQueue)
}
)
}
}
The code mostly works, but in some scenarios, unexpected behavior occurs:
Scenario 1:
Task 2
from In Progress
to To Do
--> Works fine.Task 1
from To Do
to In Progress
--> Works fine.Task 4
from To Do
to In Progress
--> BUG: "Task 1" is duplicated, and Task 4
doesn't move.Scenario 2:
Task 1
from To Do
to To Do
(same queue) --> works fine.Task 4
from To Do
to To Do
(same queue) --> BUG: nothing happens.When debugging, i noticed that sometimes the wrong task is passed to the onTaskDrop
lambda. For example, even though i'm dragging Task 1
, a different task gets processed.
It seem like the localState
passed in the drag and drop process might not always match the dragged task.
The issue seems related to task ordering in the queue!
What could be causing these issues, and how can i fix them?
Please use a key
to tell Compose how to uniquely identify each TaskCard
in your QueueTask
Composable. Then Jetpack Compose can remove exactly the one TaskCard
Composable corresponding to the removed object from the tasks
List.
tasks.forEach { task ->
key(task.title) {
TaskCard(
task = task,
queueType = queueType,
modifier = Modifier
.padding(vertical = 4.dp)
)
}
}
I could not quite figure out under which exact circumstances the code without key
starts to fail, but I now just follow the practice to always specify a key
whenever I display Composables in a forEach
loop on data that can change.
Note that in production code, you would add a unique ID to the Task
class instead of using the title
as a key
.