I'm learning Compose, the following code is from the article.
The author use var toolbarTitle by remember { mutableStateOf("Home") }
only for a title, is it necessary ?
I think var toolbarTitle= mutableStateOf("Home")
is enough, right?
Source Code
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
JetpackComposeScaffoldLayoutTheme {
// A surface container using the 'background' color from the theme
Surface(color = MaterialTheme.colors.background) {
var toolbarTitle by remember {
mutableStateOf("Home")
}
val scaffoldState =
rememberScaffoldState(rememberDrawerState(initialValue = DrawerValue.Closed))
val scope = rememberCoroutineScope()
Scaffold(
modifier = Modifier.background(Color.White),
scaffoldState = scaffoldState,
topBar = {
AppToolbar(
scaffoldState = scaffoldState,
scope = scope,
toolbarTitle = toolbarTitle
)
}, drawerContent = {
DrawerContent(scaffoldState = scaffoldState, scope = scope)
},
...
)
}
}
}
}
}
CodePudding user response:
If you don't use remember
the value will reset again to Home
on every recomposition by using remember
the value will be persisted even after a recomposition
by the way recomposition means when the composable renders again which can happen a lot of times when something changes on the screen and needs to be rendered again
CodePudding user response:
I think, if the article is from a reputed source, the variable might have some further usage in the project. The very reason for initialising the variable as a MutableState
is that the developer wants recompositions to occur upon the change of this value.
If this was not the case, it could have been just var title = "Home"
, or better instead just use "Home" in the parameter, no need of a variable at all. You see, if you are creating a MutableState
, in most scenarios, it is useless to declare it without using remember
. In fact, the only scenario I can think of, to declare a MutableState
without remeber is to trigger recompositions manually using the var
as a trigger.
Anyway, most of the times, you want to read the value of the var
that is declared MutableState
. If any modifications are made to the value of the var
, then a recomposition is triggered. Now, if you declare it without any remember
ance, the value will be re-initlaised to whatever you provided as the initial value. The updated value is gone for good in this case.
Hence, in the latest versions of the compiler, I think it will not even allow you to create a MutableState
var without using remember. If not a compile-time error, I'm sure it gives at least a warning (though I am almost certain it won't allow you to compile, which makes me think Compose Developers do not want us to trigger dummy recompositions!)
PS: The recompositions can be triggered manually by using remember
too, so I guess that was not their motto.