Home > Software engineering >  I know it is not null, but Dart doesn't know that. How do I tell it?
I know it is not null, but Dart doesn't know that. How do I tell it?

Time:11-02

The code Dart is complaining about:

Map<String,int> get_frequency(String text) { 
  Map<String,int> retval = {};
  for (int i = 0; i<text.length;   i) { 
    retval[text[i]] = retval[text[i]] ?? 0;
    retval[text[i]]  ; //<---- this is where dart is complaining.*
  }
  return retval;
}

void main() {
  const paragraphOfText = 'Once upon a time there was a Dart programmer who '
      'had a challenging challenge to solve. Though the challenge was great, '
      'a solution did come. The end.';
  var data = get_frequency(paragraphOfText);
  print(data);
}

Obviously the line marked with (*) can not be null, so how do I tell that to Dart? I tried the null assertion operator (!), but that didn't work.

Null Safety is enabled.

Error message:

challenge2.dart:5:20: Error: Operator ' ' cannot be called on 'int?' because it is potentially null.
    retval[text[i]]  ;
                   ^
challenge2.dart:5:20: Error: A value of type 'num' can't be assigned to a variable of type 'int'.
    retval[text[i]]  ;
                   ^

CodePudding user response:

A possible solution is to change the line

    retval[text[i]]  ; //<---- this is where dart is complaining.*

into

    retval[text[i]] = retval[text[i]]!   1;

Just figured it out.

  •  Tags:  
  • dart
  • Related