Flutter BMI计算器报'>='方法空值调用错误排查
Flutter BMI计算器
_bmi为null报错修复方案 问题表现
- 跟随App Brewery平台Angela教程开发BMI计算器Flutter应用时,实例化
CalculatorBrain对象并传入height、weight构造参数后,calculator_brain.dart中的私有属性_bmi始终为null - 仅手动给
_bmi初始化固定数值时程序可正常运行,触发报错为NoSuchMethod '>=' was called on null
根因定位
- 变量作用域错误:
CalculateBMI()方法内重复声明了局部变量double _bmi,计算逻辑仅给方法内的局部变量赋值,类级别的私有属性_bmi从未被赋值,默认值为null - 方法调用顺序错误:路由传参时优先调用了依赖
_bmi值的getInterpritation()、getResult()方法,此时尚未执行BMI计算逻辑给_bmi赋值,即使修正作用域问题,顺序错误仍会导致读取到null值
修复步骤
- 修正
CalculatorBrain类的变量作用域问题,删除CalculateBMI()方法内重复的_bmi类型声明,直接给类属性赋值:
class CalculatorBrain { CalculatorBrain({ @required this.Getheight, @required this.Getweight, }); final int Getheight; final int Getweight; double _bmi; String CalculateBMI() { // 移除前面的double关键字,不再声明局部变量,直接赋值给类属性_bmi _bmi = Getweight / pow(Getheight / 100, 2); return _bmi.toStringAsFixed(1); } String getResult() { if (_bmi >= 25) { return 'Overweight'; } else if (_bmi > 18.5) { return 'Normal'; } else { return 'Underweight'; } } String getInterpritation() { if (_bmi >= 25) { return 'You have a higher than normal body weight, Try excerise more'; } else if (_bmi > 18.5) { return 'You have a Normal body weight, Good Job ! '; } else { return 'You have a Low than normal body weight, Try eating More !'; } } }
- 调整计算按钮点击逻辑的方法调用顺序,先执行BMI计算完成
_bmi赋值,再获取结果文本和解读文本传参:
bottonButton( buttonTitle: 'Calculate', onTap: () { CalculatorBrain calc = CalculatorBrain(Getheight: height, Getweight: weight); // 优先执行计算逻辑,完成_bmi赋值 final bmiVal = calc.CalculateBMI(); Navigator.push( context, MaterialPageRoute( builder: ((context) => ResultsPage( interpritation: calc.getInterpritation(), ResultText: calc.getResult(), bmiResults: bmiVal, )), ), ); }, ),
可选优化
可将BMI计算逻辑移入CalculatorBrain的构造函数,实例化时自动完成_bmi赋值,从根源避免调用顺序错误:
class CalculatorBrain { CalculatorBrain({ @required this.Getheight, @required this.Getweight, }) { // 构造实例时直接计算_bmi值 _bmi = Getweight / pow(Getheight / 100, 2); } final int Getheight; final int Getweight; double _bmi; String CalculateBMI() { return _bmi.toStringAsFixed(1); } // getResult、getInterpritation方法逻辑保持不变 }
内容的提问来源于stack exchange,提问作者Ram Gupta
相关产品推荐
相关产品推荐

