I have composable function in there’s some code is duplicate in if - else condition. Both if - else have same type of UI but different component. Inside if - else UI logic is similar to this answer. I want same UI logic in here.
Xyz
@Composable
fun Xyz(
    isTrue:Boolean,
    verticalArrangement: Arrangement.Vertical
) {
    AnimatedVisibility(true) {
        Column(
            modifier = Modifier
                .padding(10.dp)
                .fillMaxHeight()
                .verticalScroll(rememberScrollState()),
            verticalArrangement = verticalArrangement
        ) {
            if (isTrue) {
                Column(
                    modifier = Modifier
                        .verticalScroll(rememberScrollState())
                        .weight(1f),
                    horizontalAlignment = Alignment.CenterHorizontally,
                ) {
                    Image() // Duplicate code
                    Text() // Duplicate code
                    Image()
                    // more item in here
                }
                Column {
                    Button { action }
                    Button { action }
                }
            } else {
                Column(
                    modifier = Modifier
                        .verticalScroll(rememberScrollState())
                        .weight(1f),
                    horizontalAlignment = Alignment.CenterHorizontally,
                ) {
                    Image() // Duplicate code
                    Text() // Duplicate code
                    Image()
                    // more item in here
                }
                Column {
                    Button { action }
                }
            }
        }
    }
}
I am adding @Preview code for some understanding
@Preview
@Composable
fun XyzPreviewTop(){
    Theme {
        Xyz(false, Arrangement.Top)
    }
}
@Preview
@Composable
fun XyzPreviewSpaceBetween(){
    Theme {
        Xyz(false, Arrangement.SpaceBetween)
    }
}
@Preview
@Composable
fun XyzPreviewOneSpaceTop(){
    Theme {
        Xyz(true, Arrangement.Top)
    }
}
@Preview
@Composable
fun XyzPreviewOneSpaceBetween(){
    Theme {
        Xyz(true, Arrangement.SpaceBetween)
    }
}
- Inside - if - elsecondition I had mention- Duplicate codewhich means that code is using in both condition.
- How can we optimise - ifcondition of both- Columnwith- elsecondition of both- Column.
If you have question please ask me. Many Thanks
 
                        
You can use slot-based layouts of Jetpack Compose which increases reusability a lot.
Slot is basically creating content:
@Composable () -> Unitlike params like Scaffold, TopAppBar and other Composables have.And you also create a ColumnScope receiver for content:
@Composable ColumnScope.()-> Unitwhich will let you call scope specific modifiers likeModifier.weightinside your content