Home > Back-end >  Reuse @Composable container for a list of items
Reuse @Composable container for a list of items

Time:10-21

data class object1()

data class object2()

In my @Composable screen I have 2 tabs, every single display a list with items.

when (tabToDisplay) {
    TabCategory.1-> Section1(list = listOf<object1>())
    TabCategory.2-> Section2(list = listOf<object2>())
}

@Section1 and @Section2 is the same composable with

 Column(){
    list.forEach {
       UiItem1()
   //or
       UiItem2()
    }
}

The only difference inside is the type of item I'm creating.

Question: How I can simplify my code to have only 1 @Composable section for my list object

CodePudding user response:

Create a parentClass for both models, lets say ParentObjClazz

Keep a single composable @Section and that takes TabCategory and list of ParentObjClazz

@Composable
fun Section(tabCategory: TabCategory, list: List<ParentObjClazz>) {
  //...
}

Cast the objects and populate the view according to tabCategory or child class type checking

CodePudding user response:

You can add a generic parameter and a content builder to your Section:

@Composable
fun<T> Section(list: List<T>, itemContent: @Composable (T) -> Unit) {
    Column(){
        list.forEach {
            itemContent(it)
        }
    }
}

Then you can it like this:

when (tabToDisplay) {
    TabCategory.1 -> {
        Section(list = listOf<Object1>()) {
            UiItem1(it)
        }
    }
    TabCategory.2 -> {
        Section(list = listOf<Object2>()) {
            UiItem2(it)
        }
    }
}

p.s. according to kotlin style guide, classes should be named in PascalCase. When you get used to this, it will increase your development speed because your eye will more easily identify the variable/class in your code. It is also required in most development commands, so it is better to get used to it right away.

  • Related