首页 > 解决方案 > 我的应用程序 throws me 方法在 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.';
    }
  }
}

你能帮我理解这个错误吗?

标签: flutterdart

解决方案


可能您正在调用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';
    }
  }
}

推荐阅读