【问题标题】:Correct declaring of a class in Dart在 Dart 中正确声明一个类
【发布时间】: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
}
  1. 为什么我可以访问变量,即使它设置为私有?
  2. 为什么late关键字会报错,变量是在构造函数调用时设置的?
  3. 我需要在构造函数中写“Book({required String this.title});”还是“Book({required String title});”就像例子中的一样?如果没关系,为什么?

感谢您的帮助! 本杰明

【问题讨论】:

    标签: class dart


    【解决方案1】:

    您的构造函数没有初始化变量!

    应该是:

      Book({required String title, required String author, required int pageCount})
          : _title = title,
            _author = author,
            _pageCount = pageCount;
    
    

    否则,_author 字段根本没有设置,读取未设置的延迟字段是错误的。

    您不能使用 this.something,因为字段具有私有名称 (_author),而命名参数不能具有私有名称。否则这将是正确的方法。相反,您需要有公共命名的参数,然后使用该值来初始化初始化列表中的字段。

    随着这一变化,字段也不需要是late,而是可以是最终的:

    class Book {
      final String _title;
      final String _author;
      final int _pageCount;
    
      Book({required String title, required String author, required int pageCount})
          : _title = title,
            _author = author,
            _pageCount = pageCount;
    }
    

    您可以从同一个库中访问私有变量,因为 Dart 隐私是基于的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-12
      • 1970-01-01
      • 2015-10-23
      相关资源
      最近更新 更多