【问题标题】:Null safety in flutter and Dart颤振和飞镖中的空安全
【发布时间】:2022-01-25 07:39:18
【问题描述】:
class CalculatorBrain {
  final int height;
  final int weight;

  double _bmi;

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

  String calculateBMI() {
    double _bmi = weight / pow(height / 100, 2);
    return _bmi.toStringAsFixed(2);
  }

  String getResult() {
    if (_bmi >= 25) {
      return "OverWeight";
    } else if (_bmi > 18.5 && _bmi < 25) {
      return "Normal";
    } else {
      return "UnderWeight";
    }
  }
}

我尝试添加 late 关键字并使用了 double ? _bmi 但它们都不起作用。

【问题讨论】:

  • 请突出显示您面临错误的位置,并在可能的情况下附加堆栈跟踪。
  • 你能分享错误代码和 j=Just try 吗?替换为!

标签: dart dart-null-safety


【解决方案1】:

这行得通:

class CalculatorBrain {
 final int height;
 final int weight;

  late double _bmi;

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

  String calculateBMI() {
    _bmi = weight / ((height / 100) * (height / 100));
    return _bmi.toStringAsFixed(2);
  }

  String getResult() {
    if (_bmi  >= 25) {
      return "OverWeight";
    } else if (_bmi  > 18.5 && _bmi <25) {
      return "Normal";
    }
    else {
      return "UnderWeight";
    }
  }
}

void main() {
  final brain = CalculatorBrain(height: 180, weight: 80);
  
  brain.calculateBMI();
  
  print(brain.getResult());
}

然而,这是可怕的类设计。我会假设这是一项学校练习,而您并没有将其发展为专业人士。


一个稍微好一点的类设计,它不依赖late 变量来隐藏这样一个事实,即只有当程序员知道必须调用函数的魔术顺序时,类才起作用:

class BodyMassIndex {
  final int height;
  final int weight;
  final double value;

  BodyMassIndex({required this.height, required this.weight}) 
    : value = (weight / ((height / 100) * (height / 100)));

  String get meaning {
    if (value  >= 25) {
      return "OverWeight";
    } else if (value  > 18.5 && value <25) {
      return "Normal";
    }
    else {
      return "UnderWeight";
    }
  }
}

void main() {
  final bmi = BodyMassIndex(height: 180, weight: 80);
  
  print("value: ${bmi.value}");
  print("meaning: ${bmi.meaning}");
}

作为准则,null 安全性取决于您毫不含糊地告诉编译器它们应该做什么。如果您的编译器无法理解您,这可能意味着您没有很好地解释它,也就是“编程”。因此,如果您遇到空值安全问题,实际上并不是空值安全问题,而是您的程序逻辑以及您编写它的方式。

【讨论】:

    【解决方案2】:

    从以下函数中删除双关键字:

     String calculateBMI() {
        double _bmi = weight / pow(height / 100, 2);
    ...
    

    并将您的类属性 double _bmi 更改为 late double _bmi

    【讨论】:

      猜你喜欢
      • 2021-07-27
      • 2021-12-07
      • 1970-01-01
      • 2019-08-02
      • 2021-06-10
      • 2020-08-12
      • 2020-12-25
      • 2020-11-05
      • 2018-11-02
      相关资源
      最近更新 更多