Home > front end >  The operator '>=' can't be unconditionally invoked because the receiver can be �
The operator '>=' can't be unconditionally invoked because the receiver can be �

Time:12-31

here the code

all operator can't be invoked because the receiver cab be 'null'

class Bmicalculator {
  final height;
  final weight;
  double? _bmi;

  Bmicalculator({this.height, this.weight});

  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';
    }
  }

please solve the essue

CodePudding user response:

On your class level, _bmi is nullable double double? _bmi;.

you can do it like

 String getResult() {
    if(_bmi==null){
      return "got null on BMI";
    }
    else if (_bmi! >= 25) {
      return 'overweight';
    } else if (_bmi! >= 18.5) {
      return 'Normal';
    } else {
      return 'underWeight';
    }
  }

! is use If you know that an expression never evaluates to null.

Learn more about null-safety

CodePudding user response:

use null safe !

 String getResult() {
    if (_bmi! >= 25) { // here need to change 
      return 'overweight';
    } else if (_bmi! >= 18.5) {// here need to change 
      return 'Normal';
    } else {
      return 'underWeight';
    }
  }
  • Related