Flutter BMI计算器报错:The method '/' was called on null 求助
问题定位与解决方案
这个错误的根源非常明确:你在创建CalculatorBrain实例的时候没有传入height和weight参数,导致这两个属性的值为null,当调用calculateBMI()方法执行height / 100时,自然就会抛出The method '/' was called on null的空指针错误。
错误代码分析
先看你创建计算器对象的这段代码:
CalculatorBrain calculationBrain = CalculatorBrain(); // 这里完全没有传入height和weight!
你的CalculatorBrain构造函数是需要接收这两个参数的:
CalculatorBrain({this.height, this.weight});
但实例化时没有传递任何参数,所以height和weight都保持初始的null状态,执行除法运算时直接触发了错误。
具体解决方案
1. 传入实际的身高体重参数
在创建CalculatorBrain的时候,必须传入用户在输入页面选择/输入的真实身高、体重值。假设你在输入页面有对应的状态变量(比如_currentHeight和_currentWeight),修改代码如下:
BottomButton( buttonTitle: 'CALCULATE', onTap: () { // 传入输入页面获取到的真实身高体重 CalculatorBrain calculationBrain = CalculatorBrain( height: _currentHeight, // 替换成你输入页面的身高变量 weight: _currentWeight // 替换成你输入页面的体重变量 ); Navigator.push( context, MaterialPageRoute( builder: (context) { return Results( bmiResult: calculationBrain.calculateBMI(), resultText: calculationBrain.getResult(), interpretation: calculationBrain.getInterpretation(), ); }, ), ); }, ),
2. 增强代码健壮性(可选)
为了避免以后再出现类似的疏忽,你可以给构造函数的参数加上@required注解,强制调用者必须传入参数:
import 'dart:math'; import 'package:flutter/foundation.dart'; // 需要导入这个包来用@required class CalculatorBrain { // 添加@required,确保调用时必须传入参数,IDE会直接提示错误 CalculatorBrain({@required this.height, @required this.weight}); int height; int weight; double _bmi; // ... 其他方法保持不变 }
另外,也可以在calculateBMI()方法里添加空值检查,提前处理异常情况:
String calculateBMI() { if (height == null || weight == null) { // 可以抛出明确的异常,或者返回提示字符串 throw ArgumentError('身高和体重参数不能为空'); // 或者返回友好提示:return '请先输入身高体重'; } _bmi = weight / pow(height / 100, 2); return _bmi.toStringAsFixed(1); }
验证修复
修改完成后,确保用户在输入页面已经正确设置了身高和体重的值,再点击"CALCULATE"按钮,就可以正常计算BMI并跳转到结果页面了。
内容的提问来源于stack exchange,提问作者Jimmyjbk
相关产品推荐
相关产品推荐

