class 实例的字符串变为空。为什么? (飞镖扑腾)

The String of an instance of a class becomes null. why? (dart flutter)

当我打印 q1 时它为空。我希望看到打印出来的问题。

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;
  }
}

只需尝试将您的构造函数更改为

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

dart 中任何实例变量的默认值将始终为 null。

因此,在您的情况下,questionTextquestionAnswer 的值也将为 null,因为 dart 中的所有内容都是对象。

另一种方法是使用 this 关键字

class Question {
 String questionText;
 bool questionAnswer;

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

然后像这样使用它

void main() {
  Question q1 = Question(questionText: 'question text', questionAnswer: false);

  print(q1.questionAnswer);
}

here is the dart pad