我的应用程序抛出了我方法被调用为null

问题描述

我制作了一个应用,并创建了一个简单的逻辑。但是当我运行它会把我扔掉

The method '>' was called on null.
Receiver: null
Tried calling: >(25)

我的意思是进行基本的数学比较,我不知道为什么会这样,这是我的文件

import 'dart:math';

class CalculatorBrain {
  CalculatorBrain({this.height,this.weight});

  final int height;
  final int weight;

  double _bmi;

  String calculateBMI() {
    double _bmi = weight / pow(height / 100,2);
    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 '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 aa lower than normal body weight. You can eat a bit more.';
    }
  }
}

您能帮助我理解此错误吗?

解决方法

在将值分配给getResult()之前,您可能正在调用getInterpretation()_bmi

为防止这种情况,您可能需要在比较之前检查_bmi是否为null。这是您的getResult函数的示例:

String getResult() {
  if (_ bmi != null){
    if (_bmi >= 25) {
      return 'Overweight';
    } else if (_bmi > 18.5) {
      return 'Normal';
    } else {
      return 'Underweight';
    }
  }
}
,

calculateBMI()中,您通过声明其类型来声明新的局部变量_bmi,因此类_bmi的{​​{1}}字段仍为空。只需删除CalculatorBrain_bmi变量的类型声明即可。 您也可以将calculateBMI()更改为getter并完全删除calculateBMI()字段。并标记_bmiheight为必填项。另外,您可以添加断言以确保该值大于0并且不为空。

weight