如何在main.dart的字符串插值中使用IMCCalculator类返回的bmi变量?
如何在main.dart文件的字符串插值中使用IMCCalculator.dart类返回的bmi变量?
实现步骤
- 转换输入类型:从文本控制器获取的身高、体重是字符串,需先转为
double类型,因为IMCCalculator.returnIMCPerson方法仅接收数值参数。 - 调用计算方法:通过
IMCCalculator.returnIMCPerson传入转换后的身高、体重,得到包含计算后BMI值的Person实例。 - 引用bmi属性:在字符串插值中直接调用该实例的
bmi属性,由于已经通过Visibility的条件校验输入不为空,可安全使用!断言非空。
修改后的main.dart代码片段
推荐封装成方法,让代码更清晰:
Visibility( visible: _nameController.text.isNotEmpty && _heightController.text.isNotEmpty && _weightController.text.isNotEmpty, child: Text( '${_nameController.text}, seu IMC é ${_getCalculatedBmi()}', style: Theme.of(context).textTheme.titleLarge, textAlign: TextAlign.center, ), ), // 封装BMI计算逻辑 double _getCalculatedBmi() { double height = double.parse(_heightController.text); double weight = double.parse(_weightController.text); Person personWithBmi = IMCCalculator.returnIMCPerson(height, weight); return personWithBmi.bmi!; }
如果想直接在插值中处理(代码相对紧凑):
Visibility( visible: _nameController.text.isNotEmpty && _heightController.text.isNotEmpty && _weightController.text.isNotEmpty, child: Text( '${_nameController.text}, seu IMC é ${IMCCalculator.returnIMCPerson(double.parse(_heightController.text), double.parse(_weightController.text)).bmi!}', style: Theme.of(context).textTheme.titleLarge, textAlign: TextAlign.center, ), ),
补充说明
- 若用户输入非合法数字,
double.parse会抛出异常,建议额外添加输入校验(比如用double.tryParse判断是否为null),避免程序崩溃。 - 原Person类和IMCCalculator类代码无需修改:
Person类代码
class Person { String? name; double? weight; double? height; double? bmi; Person({this.name, required this.weight, required this.height, this.bmi}); }
IMCCalculator类代码
import 'models/person.dart'; class IMCCalculator { static double calculate(Person person) { double heightInMeters = person.height! / 100.0; return person.weight! / (heightInMeters * heightInMeters); } static Person returnIMCPerson(double height, double weight) { double bmi = calculate(Person(height: height, weight: weight)); return Person(weight: weight, height: height, bmi: bmi); } }
内容的提问来源于stack exchange,提问作者Caio
相关产品推荐
相关产品推荐

