Leave a rating/review
In this episode, you’ll use the LazyColumn to display the list of your todos.
Before creating your UI components, create a new data package. Inside this package, create a new data class named TaskList. This class will be used to represent a todo. Add the following code to the class:
@Parcelize
data class TaskList(
val name: String,
val tasks: List<String> = listOf()
) : Parcelable
The data class has two properties:
-
name- This is a string that will be used to store the name of the todo. -
tasks- This is a list of strings that will be used to store the list of tasks for the todo.
The class has also been annotated with the @Parcelize annotation. This annotation is used to generate the Parcelable implementation for the class. The Parcelable interface is used to pass the class between activities and fragments. It currently shows errors since you haven’t set up the Parcelize plugin. To set it up, open the app module build.gradle.
Add the following code to the file in the below the org.jetbrains.kotlin.android plugin:
id 'kotlin-parcelize'
Do a gradle sync to apply the changes.
Head back to your TaskList class and resolve the errors by adding the import statements as prompted by the IDE.
Next, inside your views package, create a new file name TaskListScreen. This file will contain all the various Ui components that will display the list of your todos. Create a composable function named TaskListContent** with the following code:
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import com.kodeco.android.listmakerscript.data.TaskList
@Composable
fun TaskListContent(modifier: Modifier, tasks: List<TaskList>, onClick: (String) -> Unit) {
LazyColumn(
modifier = modifier,
content = {
items(tasks) {
ListItemView(
value = it.name,
onClick = onClick
)
}
}
)
}
Here, you’ve created a new composable function named TaskListContent that will display the list of todos. The function has three parameters:
-
modifier- This will be used to apply various modifiers to theLazyColumncomposable. -
tasks- Contains the list of todos to be displayed. -
onClick- This function is called when the user clicks on a todo. The function takes a string parameter that will be used to pass the name of the todo.
Inside the function, you’ve used the LazyColumn composable to display the list of todos. The LazyColumn composable has the following parameters:
-
modifier- This is similar to the modifiers of other Composables. -
content- This is used to display the list of todos. You passitemsinside thecontentlambda expression. You’ve passed thetasksparameter toitems. Inside theitemsblock you’ve used theListItemViewcomposable that you created earlier and passed thevalueandonClickparameters.
In the next episode, you’ll see how to use the TaskListContent composable inside a Scaffold.