**i try to writ class with its constructer in flutter,but i am facing an error and i can't fix it...i wrote it exactly the same as the guy in the tutorial ..that is the github of the guy who wrote it and you can see the class in the file question.dart in lib folder
Dart supports null safety, you need mark it like this:
class Qeustion {
late String questionText; // not be null
String? questionImage; // can be null
late bool questionAnswer;
Qeustion({required String q, String? i, required bool a}) {
questionText = q;
questionImage = i;
questionAnswer = a;
}
}
Qeustion qeustion = Qeustion(q: 'hello', a: true);
}
CodePudding user response:
This should solve it
class Question
{
String? questionText;
String? questionImage;
bool? questionAnswer;
Question({String? q, String? i, bool? a})
{
questionText = q;
questionImage = i;
questionAnswer = a;
}
}
CodePudding user response:
It's because of null safety, the tutorial you are referring won't support null safety and that's why you are getting this error. You can fix it in three ways:
Option #1: Use initialiser list
class Qeustion {
String questionText;
String questionImage;
bool questionAnswer;
Qeustion(String q, String i, bool a) : questionText = q, questionImage = i, questionAnswer = a;
}
Initialise it like:
final q = Qeustion("Q", "I", false);
Option #2: Use required keyword
class Qeustion {
String questionText;
String questionImage;
bool questionAnswer;
Qeustion({required this.questionText, required this.questionImage, required this.questionAnswer});
}
Initialise it like:
final q = Qeustion(questionText: "Q", questionImage: "I", questionAnswer: false);
Option #3: Mark it as late
class Qeustion {
late String questionText;
late String questionImage;
late bool questionAnswer;
Qeustion({String q, String i, bool a}) {
questionText = q;
questionImage = i;
questionAnswer = a;
}
}
Initialise it like:
final q = Qeustion(q: "Q", i: "I", a: false);
If you want the fields to be null, then mark it as nullable:
class Qeustion {
String? questionText;
String? questionImage;
bool? questionAnswer;
Qeustion({String? q, String? i, bool? a}) {
questionText = q;
questionImage = i;
questionAnswer = a;
}
}
Initialise it like:
final q = Qeustion(q: "Q", a: true); // i is null here
Note: I'll suggest you to use either option 1 or 2. Read more about null safety