【问题标题】:Dart Language RelatedDart 语言相关
【发布时间】:2023-02-04 20:50:58
【问题描述】:

我试图为问题创建一个类,以便我可以在我的测验应用程序的 main.dart 文件中使用它,但我遇到了一些错误。请告诉我为什么会出现这些错误,我该如何解决?

类问题:

class Question {
  String questionText;
  bool questionAnswer;

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

错误:

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.

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    问题是关于 null-safey,您需要使字段可为空,late 或在构造函数中添加 required。

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

    查找更多关于-null-safety

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-15
      • 2011-03-04
      • 2021-10-09
      • 2014-08-06
      • 2015-01-18
      • 1970-01-01
      • 2018-01-02
      • 2022-01-10
      相关资源
      最近更新 更多