Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between stringResource and LocalContext.current.getString

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?

like image 224
rbits Avatar asked Jul 30 '26 19:07

rbits


1 Answers

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.

like image 87
tomerpacific Avatar answered Aug 02 '26 10:08

tomerpacific



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!