微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决我的应用程序抛出了我方法被调用为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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?