Home > Mobile >  Non-nullable instance field '_bmi' must be initialized flutter
Non-nullable instance field '_bmi' must be initialized flutter

Time:12-22

good day i am having error with my dart code i tried using "?" but still it didn't work

i am seeing this error message "Non-nullable instance field '_bmi' must be initialized flutter"

    import 'dart:math';

class CalculatorBrain {
  final height;
  final weight;
  double _bmi;
  CalculatorBrain({
    this.height,
    this.weight,
  });
  String calculateBMI() {
    _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 interpretation() {
    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';
    } else {
      return 'you have a normal body weight you can eat a little bit more';
    }
  }
}

please how do i fix this?

CodePudding user response:

I think in your case you need to add the late modifier to you _bmi variable, like this:

 late double _bmi;

This will tell flutter that this _bmi values will be assigned at some point and can not be null after.

CodePudding user response:

Along with the answer provided by Victor Corte, there are few other ways.

  • Declate the _bmi value as late but you will have to check if it's initialized or not, otherwise it will show runtime error, which is bad
  • Declate the _bmi value as double? but you still have to take care of it being null before using it anywhere, otherwise it will show compile time error which is also bad, but not as much as runtime error.
  • Use property initializer to set _bmito a default value:
   CalculatorBrain({
    this.height,
    this.weight,
  }): _bmi = -1.0;

This approach allows to make sure that _bmi is never null.

I suggest using the 3rd approach, because it is a standard practice as well.

  • Related