Null safety in flutter and Dart

Issue

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

I have try adding late keyword and has used double ? _bmi but none of them works.

Solution

This works:

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());
}

However, it’s horrible class design. I will assume this is a school exercise and you are not developing this as a professional.


A slightly better class design, that doesn’t rely on late variables to hide the fact that there is some dark secret involved where the class only works if the programmers knows the magic order in which the functions must be called:

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}");
}

As a guideline, null-safety depends on you telling your compiler in no uncertain terms what they are supposed to do. If your compiler cannot understand you, it probably means you did not do a good job explaining it, aka "programming". So if you have problems with null safety, it isn’t actually with null-safety, it is with your program logic and how you wrote it.

Answered By – nvoigt

Answer Checked By – Katrina (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.