VS Code 上的错误,但 Dartpad 上没有。 - 字段 'percent' 应该被初始化,因为它的类型 'double' 不允许为空

Posted

技术标签:

【中文标题】VS Code 上的错误,但 Dartpad 上没有。 - 字段 \'percent\' 应该被初始化,因为它的类型 \'double\' 不允许为空【英文标题】:Error on VS Code but not on Dartpad. - Field 'percent' should be initialized because its type 'double' doesn't allow nullVS Code 上的错误,但 Dartpad 上没有。 - 字段 'percent' 应该被初始化,因为它的类型 'double' 不允许为空 【发布时间】:2021-03-05 17:10:38 【问题描述】:

我正在尝试运行此代码:

void main() 
  var studentSample = Student();
  studentSample.name = "Peter";
  print(studentSample.name);

  studentSample.percentage = 438;
  print(studentSample.percentage);


class Student 
  String name;

  double percent;

  set percentage(double marksSecured) 
    percent = (marksSecured / 500) * 100;
  

  double get percentage 
    return percent;
  

在 Visual Studio Code 上运行时,出现错误提示

main.dart:13:10: Error: Field 'percent' should be initialized because its type 'double' doesn't allow null.
  double percent;

但是,它可以在 DartPad 上运行,结果如下:

Peter
87.6

如何让 VS Code 也运行这段代码?

【问题讨论】:

【参考方案1】:

新标准将使用Null Safety

double? percent;

【讨论】:

【参考方案2】:

只需初始化percent

double percent = 0.0;

【讨论】:

以上是关于VS Code 上的错误,但 Dartpad 上没有。 - 字段 'percent' 应该被初始化,因为它的类型 'double' 不允许为空的主要内容,如果未能解决你的问题,请参考以下文章