Using Null Safety in classes
While you’ve seen the basics of Null Safety in the previous recipe, you should also be aware of a few rules that should drive the way you design classes in Dart.
Getting ready
Create a new pad in Dartpad and remove the default code in the main
method.
How to do it...
Let's see an example of a plain Dart class, with two properties. Follow these steps:
- Add a new class, with two strings and no value:
class Person {
String name;
String surname;
}
Note the compile error telling that the two fields are non-nullable
In the Person class, create a constructor that gives a value to the fields:
Person(this.name, this.surname);
Note that the error is now fixed.
Add a named constructor, that takes a map of String, dynamic and creates an instance of Person:
Person.fromMap(Map<String, dynamic> map) {
name = map['name'];
surname = map['surname'];
}
Note the compile errors that shows in the console, requiring an...