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
You are wrong, this error is not thrown for this piece of code:
Instead, the error is relative to this code:
Either
totalPerSection
is stillnull
at the time you are using it, or you are trying to access anindex
oftotalPerSection
that does not exist (rememberindex
starts at 0)It throw that error on the line
because
totalPerSection[section]!
instead ofscores[section] ?? 0
like you thinkYou should check
totalPerSection[section]
value, i’m pretty sure this is nulli think this is the error:
totalPerSection[section]!
Null check operator is this mark ":
!
.scores[section]
is nullable , and you already set0
when its null,but you miss
totalPerSection[section]
is alsonullable
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