Reader small image

You're reading from  Flutter Cookbook, Second Edition - Second Edition

Product typeBook
Published inMay 2023
Reading LevelIntermediate
PublisherPackt
ISBN-139781803245430
Edition2nd Edition
Languages
Tools
Right arrow
Author (1)
Simone Alessandria
Simone Alessandria
author image
Simone Alessandria

Simone Alessandria wrote his first program when he was 12. It was a text-based fantasy game for the Commodore 64. Now, he is a trainer (MCT), author, speaker, passionate software architect, and always a proud coder. He is the founder and owner of Softwarehouseit. His mission is to help developers achieve more through training and mentoring. He has authored several books on Flutter, including Flutter Projects, published by Packt, and web courses on Pluralsight and Udemy.
Read more about Simone Alessandria

Right arrow

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:

  1. 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...

lock icon
The rest of the page is locked
Previous PageNext Page
You have been reading a chapter from
Flutter Cookbook, Second Edition - Second Edition
Published in: May 2023Publisher: PacktISBN-13: 9781803245430

Author (1)

author image
Simone Alessandria

Simone Alessandria wrote his first program when he was 12. It was a text-based fantasy game for the Commodore 64. Now, he is a trainer (MCT), author, speaker, passionate software architect, and always a proud coder. He is the founder and owner of Softwarehouseit. His mission is to help developers achieve more through training and mentoring. He has authored several books on Flutter, including Flutter Projects, published by Packt, and web courses on Pluralsight and Udemy.
Read more about Simone Alessandria