Ad space (banner)
Lesson 12 / 20

Constructors

This lesson covers the various ways to write a constructor in Dart.

The Animal(this.name) used in the previous lesson is the shorthand constructor form. Dart offers several others as well, including named constructors.

Alongside the ordinary constructor, the sample code adds a named constructor — Animal.baby(this.name) : age = 0; — for creating a baby animal.

A common early stumble is knowing when to use several constructors. Named constructors help exactly when you want a different way of initialising for each use case.

In professional work, Flutter widgets make heavy use of named constructors such as Text.rich().

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Dart directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)