Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

_CastError Null check operator used on a null value flutter

Am a bit lost and been scratching my head for a couple of days, I am getting this error

Null check operator used on a null value

On this piece of code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 percent = (scores[section] ?? 0 / totalPerSection[section]!) * 100;

the section inside here (scores[section] ?? 0 is throwing a null pointer, but the value has data on the code above. Here is a more detailed code

   num getSectionScore(int section) {
    log("getSectionScore($section) called");
    var data = scores[section] ?? 0;
    log("getSectionScoredata($data) called");
    return scores[section] ?? 0;
  }
  num getSectionPtsPoss(int section) {
    return totalPerSection[section]!;
  }
  String getPercentage(int section) {
    log("getPercentage($section) called");
    num percent = 0;
    try {
      percent = (scores[section] ?? 0 / totalPerSection[section]!) * 100;
    } on NoSuchMethodError catch (_) { }

    if (percent % 1 == 0.0) { // if number is an int, return it as is
      return percent.truncate().toString();
    } else if (percent % 10 == 0.0) {  // else if num comes out to an even tenth (ex 0.1), return with 1 decimal
      return percent.toStringAsFixed(1);
    } else {
      return percent.toStringAsFixed(2);
    }
  }

This the function am using to get the sections and scores. When I do a console log on this bit here

var data = scores[section] ?? 0;
        log("getSectionScoredata($data) called");

no null pointer is getting thrown, as when the scores[section] is found to be null, 0 is being passed. Why am I getting the error on this line percent = (scores[section] ?? 0 and I am passing a default value if the section is found to be null .

Any help on what am doing wrong is appreciated.

>Solution :

It throw that error on the line

percent = (scores[section] ?? 0 / totalPerSection[section]!) * 100;

because totalPerSection[section]! instead of scores[section] ?? 0 like you think

You should check totalPerSection[section] value, i’m pretty sure this is null

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading