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 saying 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 ofPerson
:Person.fromMap(Map<String, dynamic> map) { name = map['name']; surname = map...