I am following the Android Basics with Compose course, and on this page it uses stringResource(affirmation.stringResourceId)
to get the resource in the Image composable, but LocalContext.current.getString(affirmation.stringResourceId)
to do the same in the Text composable:
import androidx.compose.material3.Text
import androidx.compose.foundation.layout.padding
import androidx.compose.ui.platform.LocalContext
@Composable
fun AffirmationCard(affirmation: Affirmation, modifier: Modifier = Modifier) {
Card(modifier = modifier) {
Column {
Image(
painter = painterResource(affirmation.imageResourceId),
contentDescription = stringResource(affirmation.stringResourceId),
modifier = Modifier
.fillMaxWidth()
.height(194.dp),
contentScale = ContentScale.Crop
)
Text(
text = LocalContext.current.getString(affirmation.stringResourceId),
modifier = Modifier.padding(16.dp),
style = MaterialTheme.typography.headlineSmall
)
}
}
}
What is the difference and why does it use both in different places?
There is a key difference between using
stringResource(affirmation.stringResourceId)
or
LocalContext.current.getString(affirmation.stringResourceId)
:
The first can only be used inside of a Composable, while the other can be used anywhere assuming you have a context.
This means that the first is aware of recompositions and can trigger them (I.E. in a scenario where the locale changes), while the second option won't do that.
In the example you have given, it's not clear why it was used this way, might be an oversight.