0

I'm trying to do something that would be a basic feature in any other Object Oriented Language but for some reasons in Dart, I can't manage to do it. I'm new to Dart so this question might be dumb, but I couldn't find any answer online.

I have a property that need to be calculated once and on the constructor. This is my code so far :

class Game {
  String _wordChosen;

  Game() {
    final _random = Random();
    _wordChosen = WORDS[_random.nextInt(WORDS.length)];
  }
}

WORDS is a list defined outside the class. My error is on the Game constructor : not_initialized_non_nullable_instance_field.

I don't want to set the _wordChosen variable to a default value as that would make no sense (it would be overwritten right when the constructor is run). I also don't want to set the property as nullable as again, it would make no sense.

Titouan
  • 531
  • 4
  • 13
  • 1
    Does this answer your question? [How do I initialize non-nullable members in a constructor body?](https://stackoverflow.com/q/66725613/) – jamesdlin Mar 22 '21 at 22:46

1 Answers1

-1

i think the answer is using the keyword late to make compiler know that you will initialize the variable before using it but not now like below

late String _wordChosen;

i think this is your solution and it in null safety documents here i hope this answer helps you

  • I've come across that solution but it seems not natural, I was hoping for an answer that gives a more "natural" way of doing it, but there may isn't be. – Titouan Mar 24 '21 at 17:24