acakojic
acakojic

Reputation: 376

Needs to get value from string.xml on button onclick. @Composable invocations can only happen from the context of a @Composable function

Like the title said I need to get text from string.xml and the problem is that it gets this error:

@Composable invocations can only happen from the context of a @Composable function

@Composable
fun buttonClick() {
    var text = ""
    //needs this modifier for component click 
    var modifier: Modifier = Modifier.clickable() {
        text = stringResource(id = R.string.app_name) //this is where warning is
    }
}

This is what I need inside of the function, how can I get it?

.clickable {
    stringResource(id = R.string.app_name) 
}

Upvotes: 2

Views: 746

Answers (2)

Rajan Kali
Rajan Kali

Reputation: 12953

clickable invokes a regular function rather than @Composable function as per the docs.

stringResource is a composable function which could not be invoked from non compose scope. In order to achieve this, you could either use

  1. Get the value of string in composable and assign it on click
@Composable
fun buttonClick() {
    var text = ""
    val appName by remember { stringResource(id = R.string.app_name) }

    var modifier: Modifier = Modifier.clickable() {
        text =  appName
    }
}
  1. Save resId instead of String and use stringResource when reading it
    var textId: Int = -1

    var modifier: Modifier = Modifier.clickable() {
        textId =  R.string.app_name
    }

    //while invoking 
    stringResource(textId)
}

Upvotes: 1

khaleel_jageer
khaleel_jageer

Reputation: 1512

Try this,

val context = LocalContext.current
var text = ""
Button(
    onClick = {
        text = context.getString(R.string.app_name)
    }
) {
    Text(text = "Hit me")
}

You can use LocalContext to access getString.

Upvotes: 2

Related Questions