Non-nullable instance field 'taskTitle' must be initialized
Solution 1
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.
Solution 2
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.
paras
Updated on December 31, 2022Comments
-
paras over 1 year
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; } }
-
nvoigt almost 3 yearsWhile true, it does not actually answer the question why the code the OP posted complains about it being possibly null, while it is the preferred pattern of other languages to build non-nullable types.