Correct declaring of a class in Dart

Viewed 45

I am new to dart and I have some basicaly question to the language itself. During the last days I started with classes in dart.

Now I have a short question about how to declare a class correct.

  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. Why can I access to the variable even if it's set to private?
  2. Why does the late keyword throw an error, the variable is set during the constructor call?
  3. Do I need to write in the constructor "Book({required String this.title});", or "Book({required String title});" like in the example? If it doesn't matter, why?

Thanks for helping! Benjamin

1 Answers

Your constructor is not initializing the variables!

It should be:

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

Without that, the _author field is not set at all, and reading an unset late field is an error.

You can't use this.something because the fields have private names (_author) and named parameters cannot have private names. Otherwise that would have been the correct approach. Instead you need to have public-named parameters and then use the value to initialize the field in an initializer list.

With that change, the fields also don't need to be late and can instead be final:

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

You can access the private variables from inside the same library because Dart privacy is library based.

Related