class Quote {
String text;
String author;
Quote({ this.text, this.author });
}
In vscode, without required, it will shown me error and force me to add required inside the constructor before this.text
class Quote {
String text;
String author;
Quote({ required this.text, required this.author });
}
This is the answer that copilot recommend me to do so? But I’m confuse why does I need to add required before this.text???
2
Answers
In situation where if you want that while calling this class the value must be given those variables should be marked as required, and to do so you directly create a variable and require it, just like below.
but if you are aware that this value is not necessary to be passed while calling this class, you can make it nullable, while making it nullable either you can give it a default value or just mark it as nullable using
?
Now you can call this class with or without passing any value, but you should keep in mind that since the
text
variable is nullable and it also doesn’t have any default value, so if you didn’t pass the value to text and tried to use the value of it, it will throw and error, to overcome this you can use null check operator??
Now since neither i have passed the value to text nor it has any default value, and so it will cause an error, to overcome this you can do it like,
Now if the text value is not empty then the
myQuote.text
value will be printed else'Text is empty'
wil be printed.When you define a property without’?’ it means that the property cannot be null so when you want to create an instance of this class you must define a value of the property. if you do not want the required property you must put ‘?’ after the type which means the property can be null.