skip to Main Content

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

 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.

3

Answers


  1. You are wrong, this error is not thrown for this piece of code:

    (scores[section] ?? 0
    

    Instead, the error is relative to this code:

    totalPerSection[section]!
    

    Either totalPerSection is still null at the time you are using it, or you are trying to access an index of totalPerSection that does not exist (remember index starts at 0)

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
  3. i think this is the error: totalPerSection[section]!

    Null check operator is this mark ":!.

    scores[section] is nullable , and you already set 0 when its null,
    but you miss totalPerSection[section] is also nullable value.

    Workaroud:
    Remvoe mark ! from `totalPerSection[section], and pass default value.

    you aslo need to catch error when 0/0 if you set 0 as default value

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search