【发布时间】:2021-12-13 15:03:05
【问题描述】:
我是飞镖的新手,我对语言本身有一些基本的问题。 在最后几天,我开始学习 dart 课程。
现在我有一个关于如何正确声明类的简短问题。
void main() {
Book harryPotter =
Book(title: "Goblet of Fire", author: "J. K. Rolling", pageCount: 300);
print(harryPotter._title); // 1 -> print "A" to the console
print(harryPotter._author); // 2 -> LateInitializationError: Field '_author@18448617' has not been initialized.
}
class Book {
String _title = "A";
late String _author;
late int _pageCount;
Book(
{required String title,
required String author,
required int pageCount}); // 3
}
- 为什么我可以访问变量,即使它设置为私有?
- 为什么late关键字会报错,变量是在构造函数调用时设置的?
- 我需要在构造函数中写“Book({required String this.title});”还是“Book({required String title});”就像例子中的一样?如果没关系,为什么?
感谢您的帮助! 本杰明
【问题讨论】: