import 'dart:math';
class CalcuatorBrain {
CalcuatorBrain({this.height, this.weight});
final int? height;
final int? weight;
final double _bmi = 0;
String calculateBMI() {
double _bmi = weight! / pow(height! / 100, 2);
//double _bmi = weight! / (height! * height! ) / 100;
return _bmi.toStringAsFixed(1);
}
String getResult() {
if (_bmi >= 25) {
return 'Overweight';
} else if (_bmi < 18.5) {
return 'Normal';
} else {
return 'Underweight';
}
}
String getInterpretation() {
if (_bmi >= 25) {
return 'Try to exercise more.';
} else if (_bmi >= 18.5) {
return 'Good job,';
} else {
return 'You can eat a bit more.';
}
}
}我不明白我的代码出了什么问题。原始代码工作正常(https://github.com/londonappbrewery/BMI-Calculator-Flutter-Completed),但是它已经过时了,我的代码有一些空检查"int?“我还被迫:
double _bmi = weight! / pow(height! / 100, 2);通过添加"!“2 times.Still,我得到了同样的‘体重不足’和‘你可以多吃一点’。但BMI是不同的。有什么问题吗?
发布于 2021-09-19 18:39:39
代码中有一个错误。在getResult中,
} else if (_bmi < 18.5) {需要
} else if (_bmi >= 18.5) {。
也喜欢非空类型。我看了原来的代码,身高和体重都有默认值。这样我们就可以让它们非空了。
_bmi应在构造函数中计算。因为如果getResult在calculateBMI之前调用,它将以_bmi是0的形式返回Underweight。如果它是在构造函数中计算的,我们可以以任何顺序调用任何方法。
import 'dart:math';
class CalculatorBrain {
CalculatorBrain({
required this.height,
required this.weight,
}) : _bmi = weight / pow(height / 100, 2);
final int height;
final int weight;
final double _bmi;
String calculateBMI() {
return _bmi.toStringAsFixed(1);
}
String getResult() {
if (_bmi >= 25) {
return 'Overweight';
} else if (_bmi >= 18.5) {
return 'Normal';
} else {
return 'Underweight';
}
}
String getInterpretation() {
if (_bmi >= 25) {
return 'Try to exercise more.';
} else if (_bmi >= 18.5) {
return 'Good job.';
} else {
return 'You can eat a bit more.';
}
}
}发布于 2021-09-19 18:59:52
让我们检查一下您的代码:
final double _bmi = 0;
String calculateBMI() {
double _bmi = weight! / pow(height! / 100, 2);
// double _bmi = weight! / (height! * height! ) / 100;
return _bmi.toStringAsFixed(1);
}
String getInterpretation() {
if (_bmi >= 25) {
return 'Try to exercise more.';
} else if (_bmi >= 18.5) {
return 'Good job,';
} else {
return 'You can eat a bit more.';
}
}_bmi属性始终是0。calculateBMI方法中,计算局部变量_bmi,以遮挡_bmi属性。getInterpretation方法不使用calculateBMI方法的结果,但始终使用最终的属性值。让我们检查一下原始代码:
double _bmi;
String calculateBMI() {
_bmi = weight / pow(height / 100, 2);
return _bmi.toStringAsFixed(1);
}
String getInterpretation() {
if (_bmi >= 25) {
return 'You have a higher than normal body weight. Try to exercise more.';
} else if (_bmi >= 18.5) {
return 'You have a normal body weight. Good job!';
} else {
return 'You have a lower than normal body weight. You can eat a bit more.';
}
}_bmi属性。calculateBMI方法还更新_bmi属性。getInterpretation方法,则calculateBMI方法将使用该更新的值。结论
据我所见,您的问题与非空类型的更新无关。相反,您应该更新属性,而不是用局部变量对其进行跟踪。
参考文献
https://stackoverflow.com/questions/69245524
复制相似问题