Adding and Deleting Items

Now, we can edit our to-do items. However, the app is still pretty limited, in that we can only have exactly three to-do items. While we can now change what appears in those to-do items, we cannot add or remove any.

We really should fix that.

So, in this tutorial, we will wrap up the “glassware” portion of the app, by getting rid of the fake starter data and giving the user the ability to add new to-do items and delete existing ones.

This is a continuation of the work we did in the previous tutorial. The book’s GitLab repository contains the results of the previous tutorial as well as the results of completing the work in this tutorial.

Step #1: Trimming Our Repository

First, let’s get rid of the sample data. That is merely a matter of changing the items declaration in ToDoRepository to be:

  var items = emptyList<ToDoModel>()

We already have a save() function in the repository to add items, but we need a function to remove them as well. To that end, add this delete() function to ToDoRepository:

  fun delete(model: ToDoModel) {
    items = items.filter { it.id != model.id }
  }

Here, we just replace items with a filtered edition of items, keeping any item that has an ID different than the one that we are trying to remove.

If you now run the sample app, it runs, but we have no to-do items:

ToDo App, Showing Nothing
ToDo App, Showing Nothing

Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.