Non-nullable instance field 'taskTitle' must be initialized

Viewed 3195

I'm new to Flutter development and here in my code why i'm getting this error (Non-nullable instance field taskTitle must be initialized), despite of initialising instance field in constructor.

So, I'm assuming that whenever this class instance is created user need to provide both member mendatory, so this error should not occur (although if add late modifier this error disappear).

Please clear my doubts.

class Task {
  String taskTitle;
  bool isDone = false;

  Task(String taskTitle, bool isDone) {
    this.taskTitle = taskTitle;
    this.isDone = isDone;
  }
}
2 Answers

You are using dart null safety environment, for that, you have to either declare the taskTitle variable as a nullable variable if it can be null by defining:

String? taskTitle;

or if it won't be null, then you can say:

late String taskTitle;

which means that at a later point of time you will initialize the taskTitle variable and it won't be null.

Because the compiler cannot evaluate the body that perfectly. A body is some arbitrary code, able to throw exceptions, have side effects and generally do all kinds of nasty stuff. Use the provided means to enable dart to make sure your variable is indeed filled with something:

class Task {
  String taskTitle;
  bool isDone;

  Task(this.taskTitle, this.isDone);
}

It's a lot shorter for you too write, too.

Related