7

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?

1 Answer 1

8

There is a key difference between using

  1. stringResource(affirmation.stringResourceId) or

  2. 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.

Sign up to request clarification or add additional context in comments.

3 Comments

To make it more explicit: Always use the first one.
It's almost certainly an oversight as the description above the code block in the tutorial even says "Pass a stringResource of the affirmation.stringResourceId to the text parameter"
The getter for LocalContext.current is a composable function, so this will also only work inside of a composable.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.