Initializer Lists
Part of the Object Oriented Programming section of Coddy's Dart journey — lesson 12 of 110.
An initializer list is the code that appears after a colon in a constructor, before the constructor body. It runs before the constructor body executes and is used to initialize instance variables.
You've already seen initializer lists in previous lessons:
Point.origin() : x = 0, y = 0;The part after the colon (x = 0, y = 0) is the initializer list. Multiple initializations are separated by commas.
Initializer lists are essential when working with final variables, which must be set before the constructor body runs:
class Circle {
final double radius;
final double area;
Circle(double r)
: radius = r,
area = 3.14159 * r * r;
}
Circle c = Circle(5);
print(c.radius); // 5.0
print(c.area); // 78.53975The initializer list can also perform calculations or transformations on constructor parameters before assigning them. This is useful when you need to derive values or validate data during object creation.
You can combine the shorthand this. syntax with an initializer list:
class Rectangle {
final double width;
final double height;
final double area;
Rectangle(this.width, this.height)
: area = width * height;
}
Rectangle rect = Rectangle(4, 5);
print(rect.area); // 20.0Here, width and height are assigned via shorthand, while area is calculated in the initializer list using those values.
Challenge
EasyLet's build a box dimension calculator that uses initializer lists to compute derived values when objects are created.
You'll organize your code into two files:
box.dart: Define aBoxclass that represents a 3D box with dimensions and automatically calculated properties. Your class should have:- Three
final doublefields:length,width, andheight - Two computed
final doublefields:volumeandsurfaceArea - A constructor that takes
length,width, andheightusing thethis.shorthand, and uses an initializer list to calculatevolume(length × width × height) andsurfaceArea(2 × (length×width + width×height + height×length)) - A
display()method that prints the box information
- Three
main.dart: Import your box class and create two boxes:- A box with dimensions
3.0,4.0,5.0 - A box with dimensions
2.0,2.0,2.0
display()on each box in the order listed.- A box with dimensions
The display() method should print in this exact format:
Box: [length]x[width]x[height] | Volume: [volume] | Surface: [surfaceArea]Expected output:
Box: 3.0x4.0x5.0 | Volume: 60.0 | Surface: 94.0
Box: 2.0x2.0x2.0 | Volume: 8.0 | Surface: 24.0Cheat sheet
An initializer list is code that appears after a colon in a constructor, before the constructor body. It runs before the constructor body executes and is used to initialize instance variables.
Basic syntax with multiple initializations separated by commas:
Point.origin() : x = 0, y = 0;Initializer lists are essential for final variables, which must be set before the constructor body runs:
class Circle {
final double radius;
final double area;
Circle(double r)
: radius = r,
area = 3.14159 * r * r;
}You can combine the shorthand this. syntax with an initializer list to assign some fields directly and calculate others:
class Rectangle {
final double width;
final double height;
final double area;
Rectangle(this.width, this.height)
: area = width * height;
}The initializer list can perform calculations or transformations on constructor parameters before assigning them, useful for deriving values during object creation.
Try it yourself
import 'box.dart';
void main() {
// TODO: Create a box with dimensions 3.0, 4.0, 5.0
// TODO: Create a box with dimensions 2.0, 2.0, 2.0
// TODO: Call display() on each box in order
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesLibraries & ImportsIntroduction to OOPClasses vs ObjectsThe this KeywordMethodsInstance VariablesConstructor BasicsRecap - Simple Calculator4Null Safety
Intro to Null SafetyNullable vs Non-NullableThe ? and ! OperatorsLate Keyword & Null SafetyNull-Aware OperatorsNull Safety in ClassesRecap - User Profile System7Abstract Classes & Interfaces
Abstract ClassesAbstract MethodsInterfaces in DartImplicit InterfacesImplementing vs ExtendingMultiple InterfacesRecap - Shape Calculator10Collections & Generics
List, Set, Map OverviewType-Safe CollectionsGeneric ClassesGeneric MethodsGeneric ConstraintsIterable & IteratorRecap - Generic Storage13Advanced OOP Concepts
Composition vs InheritanceExtension MethodsCallable ClassesSealed Classes (Dart 3)Records (Dart 3)Patterns & Matching (3.0)Enums with Methods16Project: Library Management
Project OverviewBook and User Classes2Constructors in Dart
Default ConstructorNamed ConstructorsInitializer ListsConstant ConstructorsFactory ConstructorsRedirecting ConstructorsRecap - Shape Builder5Encapsulation
Public vs Private MembersThe _ Prefix ConventionLibrary-Level PrivacyGetters & Setters DepthInformation HidingRecap - Student Records8Mixins
Introduction to MixinsCreating MixinsUsing Multiple Mixinson Keyword in MixinsMixin vs InheritanceMixin vs InterfaceRecap - Animal System11Special Methods
toString() OverridehashCode & == OverrideComparable Interfacecall() MethodnoSuchMethod OverrideRecap - Custom Collection14Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy Pattern3Class Properties
Instance vs Static MembersFinal & Const FieldsLate VariablesStatic Methods & FieldsGetters and SettersRecap - Bank Account Manager6Inheritance
Basic InheritanceThe super KeywordMethod OverridingThe @override AnnotationThe final Class KeywordConstructors & InheritanceRecap - Employee Hierarchy9Polymorphism
Polymorphism BasicsPolymorphism via InterfacesRuntime Type CheckingThe is & as OperatorsCovariant KeywordRecap - Payment Processor