Android Studio Arctic Fox (Patch 3) flags, "The value true
assigned to var isVisited: Boolean
in the following composable is never used":
@Composable
fun MainView(navController: NavController) {
var isVisited by rememberSaveable { mutableStateOf(false) }
if (!isVisited) {
isVisited = true // never used?
navController.navigate("NextView")
}
Button(onClick = { navController.navigate("NextView") }) {
Text(text = "MainView")
}
}
while it is clearly working as intended: to prevent MainView
from navigating to NextView
on subsequent visits to MainView
. Here's the definition of NextView
:
@Composable
fun NextView(navController: NavController) {
Button(onClick = { navController.popBackStack() }) {
Text(text = "NextView")
}
}
Is Android Studio simply not recognizing variable usage across recompositions? Or is there a more idiomatic way to execute code conditionally upon recompositions? Thanks for any answer or pointer.
I'm building for API Level 31 with Kotlin 1.5.31, Compose 1.1.0-alpha06, navigation-compose 2.4.0-alpha04, lifecycle-runtime-ktx 2.4.0-rc01, though I've seen the same behavior on API Level 30, Kotlin 1.5.21, Compose 1.0.1, navigation-compose 2.4.0-alpha04, lifecycle-runtime-ktx 2.3.1. (I'd be happy to share my MainActivity
where I set up NavHost
with these two views or other dependency and system info if helpful.)
CodePudding user response:
TOP OF THE LINE: You can safely ignore that warning, because the purpose of warnings is to prevent developers from using unnecessary system resources. Because of some internal highlighter logic error (perhaps?), it identifies a useful variable as an unused one, but since you know you are actively using it in code flow, you can just ditch that warning. Just suppress it with an annotation if it bugs you.
BODY CONTENT:-
Don't bother, it happens at times. There seems no error to me, just try deleting the line, and then re-adding it while using as much code completion as you can. If that does not help, just compile the project, and see the build log. If it does not show the warning: var 'isVisited' is never used
, then you can relax about it, since it would then be a bug in the studio's code highlighter. Long as you don't receive any build time warnings, be sure that it does not pose any threat pertaining to performance or whatsoever.