The String of an instance of a class becomes null. why? (dart flutter)
856
Solution 1
Just try changing your constructor to
Question({String q, bool a}) {
questionText = q;
questionAnswer = a;
}
Default value of any instance variable in dart will always be null.
So, in your case value of questionText and questionAnswer will also be null as everything in dart is an Object.
Solution 2
Another way you can do this is by using the this keyword
class Question {
String questionText;
bool questionAnswer;
Question({this.questionText, this.questionAnswer});
}
and then use it like this
void main() {
Question q1 = Question(questionText: 'question text', questionAnswer: false);
print(q1.questionAnswer);
}
Author by
Martin Gressler
Updated on December 16, 2022Comments
-
Martin Gressler over 1 year
When I print q1 it's null. I expected to see the question printed.
void main() { Question q1 = Question( q: 'You can lead a cow down stairs but not up stairs.', a: false); print(q1.questionAnswer); } class Question { String questionText; bool questionAnswer; Question({String q, bool a}) { q = questionText; a = questionAnswer; } }
-
Maxim Sagaydachny over 4 yearsShould not you assign members instead of parameters? I mean questionText = q; questionAnswer = a;
-