I was trying to create a class for questions so that I can use it in main.dart
file in my Quiz App but I encountered some errors. Please tell me Why these errors came and How can I resolve them?
class Question:
class Question {
String questionText;
bool questionAnswer;
Question({String q, bool a}) {
questionText = q;
questionAnswer = a;
}
}
Errors:
Non-nullable instance field 'questionAnswer' must be initialized.
Non-nullable instance field 'questionText' must be initialized.
The parameter 'q' can't have a value of 'null' because of its type, but the implicit default value is 'null'.
The parameter 'a' can't have a value of 'null' because of its type, but the implicit default value is 'null'.
2
Answers
The issue is about null-safey, you need to make fields nullable,
late
or add required on constructor.Find more about -null-safety
Yeasin’s answer is probably what you want, but I want to expand on null safety.
so dart, the underlying language, now has something called "null safety".
This means that unless you tell dart the variable can be null, it will complain when a non-nullable variable is not given a variable.
Example
using variables that can be null comes with a host of other things to think about. so I advise looking into it. I’ve linked a really easy video on the topic (depending on your skill you might be okay to find a faster video)
https://www.youtube.com/watch?v=llM3tcpaD5k