为什么 MutableState<Float> 在调用函数时被视为 Float?

why MutableState<Float> is seen as Float when calling the function?

提问人:AboKaid 999 提问时间:7/15/2023 更新时间:7/15/2023 访问量:63

问:

`@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
}

当我调用 calculateBMI 函数时,我尝试使用 .value 函数而不仅仅是 bmi,但它也不起作用,我只是质疑为什么程序会引发不匹配错误并将 bmi 视为浮点数而不是可变状态,我一开始尝试在不调用函数中调用 bmi 的情况下执行此操作,但发现如果函数最好将其作为参数

Kotlin android-jetpack

评论


答:

2赞 mohsen 7/15/2023 #1

如果你愿意,你应该使用而不是bmi.value=by

var bmi = remember { mutableStateOf(0.0f) }