如何在构造体主体中初始化不可用的成员?
我以这种方式创建了我的班级,但是我必须初始化不可用的实例字段“文本”。尝试在此构造函数中添加初始化器表达式,或在此构造函数中添加字段初始化器,或将其标记为“迟到”。
我想知道是否有一种方法可以以“ python'样式进行此类creation”可能,谢谢。
class Lexer {
String _text;
int _pos;
String _current_char;
Lexer(String text) {
this._text = text;
this._pos = -1;
this._current_char = '';
this.advance();
}
void advance() {
this._pos++;
this._current_char = this._pos < this._text.length ? this._text[this._pos] : '';
}
}
I've created my class in Dart this way, but I'm getting the Non-nullable instance field 'text' must be initialized. Try adding an initializer expression, or add a field initializer in this constructor, or mark it 'late'.
I would like to know if there's a way to do it in a 'Python' style where this kind of class creation is possible, thank you in advance.
class Lexer {
String _text;
int _pos;
String _current_char;
Lexer(String text) {
this._text = text;
this._pos = -1;
this._current_char = '';
this.advance();
}
void advance() {
this._pos++;
this._current_char = this._pos < this._text.length ? this._text[this._pos] : '';
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这声明了几个具有类型
字符串
的成员。由于它们被声明为String
而不是String?
,因此这些成员是不可用的;它们不允许永远是null
。 (这是DART 2.12的新NULL-SAFETY功能的一部分。)DART在两个阶段中初始化对象。当构造函数的 body 运行时,DART期望所有成员变量已经初始化。因为您的成员不可拆卸,并且尚未将其初始化为非零值,所以这是一个错误。错误消息解释了您可以做什么:
使用初始化器表达式。这意味着使用 initializer list :< /p>
请注意,如果您使用同名的构造参数初始化成员,则可以使用速记:
添加字段初始化器。这意味着在类声明中初始化成员 inline 。
将您的成员标记为
late
。这意味着您保证将在任何尝试使用它们之前初始化变量。使您的成员无效,默认情况下可以隐式为null:
但是,这将要求所有访问明确检查成员在使用之前是否没有null。
您还可能要阅读: DART立即或在构造函数中分配给变量?
This declares several members with type
String
. Since they are declared asString
and not asString?
, these members are non-nullable; they are not allowed to ever benull
. (This is part of the new null-safety feature from Dart 2.12.)Dart initializes objects in two phases. When the constructor's body runs, Dart expects all member variables to already be initialized. Because your members are non-nullable and haven't been initialized to non-null values yet, this is an error. The error message explains what you can do:
Use initializer expressions. This means using an initializer list:
Note that if you're initializing members with a construction parameter of the same name, you can use shorthand:
Adding field initializers. This means initializing members inline in the class declaration.
Marking your members as
late
. This means that you promise that the variables will be initialized before anything attempts to use them.Making your members nullable, which allows them to be implicitly null by default:
However, that will require that all accesses explicitly check that the members aren't null before using them.
You also might want to read: Dart assigning to variable right away or in constructor?