Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to Parcelize data class in jetpack compose

I have data class and one variable is type of Color. I have logic to store different types of colors to show in UI i.e.

data class SubTitleModel(
    val text: String,
    val textColor: Color = Color.Black
) 

When I am passing from one activity to another activity I have to use @Parcelize i.e.

import android.os.Parcelable
import kotlinx.parcelize.Parcelize

@Parcelize
data class SubTitleModel(
    val text: String,
    val textColor: Color = Color.Black
) : Parcelable

It giving me error on Color

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Type is not directly supported by 'Parcelize'. Annotate the parameter type with '@RawValue' if you want it to be serialized using 'writeValue()'

so what does it mean? How to solve this problem? Please provide detail explanation with proper reference. Thanks

>Solution :

Another option is to pass Int or Long instead of passing Compose Color such as

data class SubTitleModel(
    val text: String,
    val textColor: Int = (0xFF000000).toInt()
)

Then in your ui

@Preview
@Composable
private fun Test() {
    val modelList = listOf(
        SubTitleModel(
            text = "SomeText"
        ),
        SubTitleModel(
            text = "SomeText2",
            textColor = Color.Red.toArgb()
        ),
        SubTitleModel(
            text = "SomeText3",
            textColor = Color.Green.toArgb()
        )
    )

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(20.dp)
            .border(2.dp, Color.Red)
    ) {
        modelList.forEach { model: SubTitleModel ->
            Text(text = model.text, color = Color(model.textColor))
        }
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading