Home > other >  Making Class and Object with Flutter
Making Class and Object with Flutter

Time:11-12

I'm trying to make a class and object but the errors that I get are

Error: Field 'questionText' should be initialized because its type 'String' doesn't allow null.
  String questionText;
Error: Field 'questionAnswer' should be initialized because its type 'bool' doesn't allow null.
  bool questionAnswer;
class Question{
  String questionText;
  bool questionAnswer;

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

CodePudding user response:

Initialization rules are more strict with this introduction of null safety in dart. See Uninitialized variables:

Instance fields must either have an initializer at the declaration, use an initializing formal, or be initialized in the constructor’s initialization list. That’s a lot of jargon. Here are the examples:

// Using null safety:
class SomeClass {
 int atDeclaration = 0;
 int initializingFormal;
 int initializationList;

 SomeClass(this.initializingFormal)
     : initializationList = 0;
}

In your case, you are using named parameters, so you need to mark them as required as well (or use positional ones)

class Question{
  String questionText;
  bool questionAnswer;

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

Alternative with initializing formal and named parameters: (Note that class fields and named parameters need to have the same name)

class Question{
  String questionText;
  bool questionAnswer;

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

CodePudding user response:

You can create objects in this way: For more you can refer to https://dart.academy/creating-objects-and-classes-in-dart-and-flutter/.

class Point {
  int x;
  int y;

  Point(int x, int y) {
    this.x = x;
    this.y = y;
  }
}

CodePudding user response:

The most important thing is that if you use named parameters, not putting "required" implies that the parameters are optional. And you cannot assign a variable of type String? (which is String or null) to a variable of type String. This is why you could not assign "q" to "questionText".

You can make the properties optional:

class Question{
  String? questionText;
  bool? questionAnswer;

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

Or you can make the parameters required:

class Question{
  String questionText;
  bool questionAnswer;

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

And a simpler way to do this is like this:

class Question{
  String questionText;
  bool questionAnswer;

  Question({required String this.questionText, required bool this.questionAnswer});
}
  • Related