Home > Enterprise >  Dart Language Related
Dart Language Related

Time:02-05

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'.

Image of Errors here.

CodePudding user response:

The issue is about null-safey, you need to make fields nullable, late or add required on constructor.

class Question {
  late String questionText;
  late bool questionAnswer;

  Question({required String q, required bool a}) {
    questionText = q;
    questionAnswer = a;
  }
}
class Question {
   String questionText;
   bool questionAnswer;

  Question({required this.questionAnswer, required this.questionText});
}

Find more about -null-safety

CodePudding user response:

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

class Question{
    String complaint; // complain because it is not initialised
    String fine = ""; // no complaint, because we have a string variable, though it is empty.
    late String lateString; // tells the compiler don't worry. I'll define it later in the constructor while the object in being created
    String nullable?; // tells the compiler this variable can be null

}

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

  • Related