Home > Software engineering >  Flutter : Null check operator used on a null value
Flutter : Null check operator used on a null value

Time:04-11

Every time I run my app. It shows

"Null check operator used on a null value".

I have shown some solutions but couldn't successfully apply them to my code. How do I solve this?

import 'dart:math';

class bmicalculator {
  bmicalculator({required this.height, required this.weight});

  int height;
  double weight;
  double? bmi;

  String Calculation() {
    bmi = weight / pow(height / 100, 2);
    return bmi!.toStringAsFixed(2);
  }

  String getResult() {
    if (bmi! >= 25) {
      return 'Overweight';
    } else if (bmi! > 18.5) {
      return 'Normal';
    } else
      return 'UnderWeight';
  }

  String getInterpretation() {
    if (bmi! >= 25) {
      return 'String 1';
    } else if (bmi! > 18.5) {
      return 'String 2';
    } else
      return 'String 3';
  }
}

CodePudding user response:

The null check operator(!) is used at getResult() and getInterpretation() functions. This operator should NOT be used if the value can be null. The bmi value can be null, so you don't use the ! operator if that can be null.

Solution

Add condition before using the bmi value like below.

String getResult() {
  if (bmi == null)
    throw Exception(); // or return 'The bmi is null!';

  if (bmi! >= 25) {
    return 'Overweight';
  } else if (bmi! > 18.5) {
    return 'Normal';
  } else
    return 'UnderWeight';
}

CodePudding user response:

this would happen when you call getResult or getInterpretation without calling Calculation previously, and the problem is that you are not initilizing the value of bmi which is a String? type and it's initial value is null, so when you try to use one of the methods getResult or getInterpretation you would get error because bmi is null,

you can solve the issue by initializing the bmi value in the constructor like:

  bmicalculator({required this.height, required this.weight}){
        bmi = weight / pow(height / 100, 2);
  }
  • Related