Flutter error: The body might complete normally

Viewed 52

I'm trying to run this function in Flutter and I'm getting the error: The body might complete normally, causing 'null' to be returned, but the return type, 'String', is a potentially non-nullable type. Try adding either a return or a throw statement at the end.

But if I add return ''; in the end it does not return any value, any solution?

String getWord() {
wordCounter += 1;
var rand = Random();
int wordLength = _words.length;
int randNumber = rand.nextInt(wordLength);
bool notUnique = true;
if (wordCounter - 1 == _words.length) {
  notUnique = false;
  return '';
}
while (notUnique) {
  if (!_usedNumbers.contains(randNumber)) {
    notUnique = false;
    _usedNumbers.add(randNumber);
    return _words[randNumber];
  } else {
    randNumber = rand.nextInt(wordLength);
  }
}

}

1 Answers

The body might complete normally, causing 'null' to be returned, but the return type, 'String', is a potentially non-nullable type. Try adding either a return or a throw statement at the end. can be resolved like the below code.

Try to return only once at the end

String getWord() {
String returnString = "";
wordCounter += 1;
var rand = Random();
int wordLength = _words.length;
int randNumber = rand.nextInt(wordLength);
bool notUnique = true;
  if (wordCounter - 1 == _words.length) {
      notUnique = false;
  } 
  while (notUnique) {
    if (!_usedNumbers.contains(randNumber)) {
       notUnique = false;
       _usedNumbers.add(randNumber);
       returnString = _words[randNumber];
    } else {
       randNumber = rand.nextInt(wordLength);
    }
  }
 return returnString;
}
Related