'Composable calls are not allowed inside the calculation parameter of inline fun
I am trying to access the dao instance of my room database which is being used to store names(This code I wrote just to get familiar to jetpack compose).
I tried to access my dao instance inside my composable function but is giving me this error -> Composable calls are not allowed inside the calculation parameter of inline fun remember(calculation: () -> TypeVariable(T)): TypeVariable(T)
My Code
@Composable
fun HomeScreen(navController: NavController){
var dao by remember{
mutableStateOf(NameDatabase.getInstance(LocalContext.current).getDao())
}
var scope = rememberCoroutineScope()
var username by rememberSaveable{ mutableStateOf("") }
Column(
modifier = Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
){
OutlinedTextField(value = username, onValueChange = {username=it})
Spacer(modifier = Modifier.height(10.dp))
Button(onClick = {
navController.navigate("showScreen/$username")
}) {
Text("Submit")
}
}
}
I am getting the error on this line
mutableStateOf(NameDatabase.getInstance(LocalContext.current).getDao())
Specifically LocalContext.current is giving this error.
PS: I have resolved this error but want to know what is the meaning of this error any why I can't get the dao instance inside remember.
Solution 1:[1]
LocalContext.current is marked with @Composable and can only be used inside an other @Composable function. remember lambda is marked with @DisallowComposableCalls, and from the name you can understand that it disallows composable calls. So it's not related to mutableStateOf, only to remember.
You can face same issue with side effects, like LaunchedEffect, or event callbacks, like clickable - in these cases there's no @DisallowComposableCalls because these are not inlined functions, and callbacks are gonna be called onside of @Composable scope.
You need to read the value outside of the function:
val context = LocalContext.current
var dao by remember {
mutableStateOf(NameDatabase.getInstance(context).getDao())
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
