manueldidonna
11/17/2020, 11:50 AMsavedInstanceState
doesn't work in a NavHost. This sample will always print '1'. Am I doing something wrong?
NavHost(navController, startDestination = "search") {
composable("search") {
var counter by savedInstanceState { 0 }
counter += 1
Log.d("counter", counter.toString())
}
}
Ian Lake
11/17/2020, 5:49 PMrememberSavedInstanceState
if you want the state to be remembered across compositionsmanueldidonna
11/17/2020, 6:29 PMsavedInstanceState
should be rememberSavedInstanceState { mutableStateOf(init()) }
. In fact my sample works if used in the Activity.setContent blockmanueldidonna
11/17/2020, 6:30 PM@Composable
fun <T> savedInstanceState(
vararg inputs: Any?,
saver: Saver<T, out Any> = autoSaver(),
key: String? = null,
policy: SnapshotMutationPolicy<T> = structuralEqualityPolicy(),
init: () -> T
): MutableState<T> = rememberSavedInstanceState(
*inputs,
saver = mutableStateSaver(saver, policy),
key = key,
init = { mutableStateOf(init(), policy) }
)
Ian Lake
11/17/2020, 7:07 PMmutableStateOf
works, but savedInstanceState
isn't working for you? Do you mind filing a bug with a sample project? https://issuetracker.google.com/issues/new?component=409828Hitanshu Dhawan
11/21/2020, 4:22 PMsavedInstanceState
to store the current theme and change it.
The issue is calling setLightTheme(!isLightTheme)
will change the theme, but after that isLightTheme
is not changed to false and the theme is not changed.
Is this a bug? or am I doing something wrong?
setContent {
val (isLightTheme, setLightTheme) = savedInstanceState { true }
MyProjectTheme(lightTheme = isLightTheme) {
val navController = rememberNavController()
NavHost(navController, startDestination = "home") {
composable("home") {
HomeScreen(
onClick = { setLightTheme(!isLightTheme) }
)
}
}
}
}
Hitanshu Dhawan
11/21/2020, 4:23 PMmanueldidonna
11/24/2020, 5:43 PMmanueldidonna
11/24/2020, 6:47 PMHitanshu Dhawan
12/14/2020, 9:49 PMHitanshu Dhawan
01/20/2021, 11:09 AMsetContent {
val (isLightTheme, setLightTheme) = remember { mutableStateOf(true) }
McComposeTheme(lightTheme = isLightTheme) {
HomeScreen {
setLightTheme(!isLightTheme)
}
}
}
But this doesn’t seem to work.
Any help here please?Hitanshu Dhawan
01/20/2021, 6:10 PM