Search code examples
androidcolorsandroid-jetpack-compose

How to use Color with rememberSaveable in Jetpack Compose?


I want to keep color after screen rotation. But this code throws an error:

var color by rememberSaveable { mutableStateOf(Color.Red) }
java.lang.IllegalArgumentException: MutableState containing Color(1.0, 0.0, 0.0, 1.0, sRGB IEC61966-2.1) cannot be saved using the current SaveableStateRegistry. The default implementation only supports types which can be stored inside the Bundle. Please consider implementing a custom Saver for this class and pass it as a stateSaver parameter to rememberSaveable().

How to implement Saver for Color?


Solution

  • Solution 1: use custom MapSaver

    val ColorSaver = run {
        val redKey = "Red"
        val greenKey = "Green"
        val blueKey = "Blue"
        mapSaver(
            save = { mapOf(redKey to it.red, greenKey to it.green, blueKey to it.blue) },
            restore = {
                Color(
                    red = it[redKey] as Float,
                    green = it[greenKey] as Float,
                    blue = it[blueKey] as Float
                )
            }
        )
    }
    

    Example of use:

    var color by rememberSaveable(stateSaver = ColorSaver) { mutableStateOf(Color.Red) }
    

    Read more in official documentation: https://developer.android.com/jetpack/compose/state#mapsaver

    Solution 2: store data state in ViewModel

    A simpler and more universal solution: you can just move all variables with complex data that are not supported by rememberSaveable into the ViewModel.