`@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun BMI() {
var bmi by remember { mutableStateOf(0.0f) }
var weight by remember { mutableStateOf("") }
var height by remember { mutableStateOf("") }
Column(
modifier = Modifier
.fillMaxSize()
.background(color = Color.White)
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
//height
Text(text = "Enter your height")
TextField(
keyboardOptions = KeyboardOptions.Default.copy(
keyboardType = KeyboardType.Decimal,
imeAction = ImeAction.Done
),
value = height,
onValueChange = { height = it }
)
Spacer(modifier = Modifier.padding(8.dp))
//weight
Text(text = "Enter your weight")
TextField(
keyboardOptions = KeyboardOptions.Default.copy(
keyboardType = KeyboardType.Decimal,
imeAction = ImeAction.Done
),
value = weight,
onValueChange = { weight = it }
)
Spacer(modifier = Modifier.padding(8.dp))
//button stuff
Button(onClick = {
calculateBMI(height, weight, bmi)
}) {
Text(text = "Calculate BMI", textAlign = TextAlign.Center)
Spacer(modifier = Modifier.padding(10.dp))
}
if (bmi > 0.0f) {
Text("Your BMI is %.2f".format(bmi))
}
}
}
}
fun calculateBMI(height: String, weight: String, bmiState: MutableState<Float>) {
val h = height.toFloatOrNull() ?: return
val w = weight.toFloatOrNull() ?: return
val bmi = w / (h * h)
bmiState.value = bmi
}
I tried to use the .value function insted of just bmi when I called the calculateBMI function but it didn't work too, I am just questioning why does the program raise a mismatch error and see bmi as a float and not a mutablestate, I tried in the beginning to do it without calling bmi in the function but found out it is better to put it as a parameter if the function
If you want bmi.value
you should use =
instead of by
var bmi = remember { mutableStateOf(0.0f) }