Constant Constructors
Part of the Object Oriented Programming section of Coddy's Dart journey — lesson 13 of 110.
A constant constructor creates compile-time constant objects. When you create objects with the same values using a const constructor, Dart reuses the same instance in memory, improving performance.
To create a constant constructor, add the const keyword before the constructor name, and ensure all instance variables are final:
class Color {
final int red;
final int green;
final int blue;
const Color(this.red, this.green, this.blue);
}
const white = Color(255, 255, 255);
const alsoWhite = Color(255, 255, 255);
print(identical(white, alsoWhite)); // trueBoth white and alsoWhite point to the exact same object in memory because they were created with identical values using a const constructor.
You can also use const constructors without the const keyword, which creates regular (non-constant) instances:
var red = Color(255, 0, 0); // Regular instance
const blue = Color(0, 0, 255); // Constant instanceConstant constructors are commonly used for immutable configuration objects, predefined values like colors or sizes, and anywhere you want to guarantee object immutability while optimizing memory usage.
Challenge
EasyLet's build a configuration system for a simple game that uses constant constructors to define immutable, reusable settings.
You'll create two files to organize your code:
difficulty.dart: Define aDifficultyclass that represents game difficulty settings. Your class should have:- Three
finalfields:name(String),enemyCount(int), andplayerLives(int) - A constant constructor that initializes all three fields
- A
display()method that prints the difficulty information
- Three
main.dart: Import your difficulty class and create three constant difficulty presets:easywith name'Easy',5enemies, and5livesmediumwith name'Medium',10enemies, and3liveshardwith name'Hard',20enemies, and1life
constkeyword. Then calldisplay()on each in the order listed above. Finally, check if twoconst Difficulty('Easy', 5, 5)objects are identical usingidentical()and print the result.
The display() method should print in this exact format:
[name]: [enemyCount] enemies, [playerLives] livesExpected output:
Easy: 5 enemies, 5 lives
Medium: 10 enemies, 3 lives
Hard: 20 enemies, 1 lives
trueCheat sheet
A constant constructor creates compile-time constant objects. When objects with identical values are created using a const constructor, Dart reuses the same instance in memory.
To create a constant constructor, add the const keyword before the constructor name and ensure all instance variables are final:
class Color {
final int red;
final int green;
final int blue;
const Color(this.red, this.green, this.blue);
}Creating constant instances with identical values results in the same object in memory:
const white = Color(255, 255, 255);
const alsoWhite = Color(255, 255, 255);
print(identical(white, alsoWhite)); // trueConst constructors can also be used without the const keyword to create regular instances:
var red = Color(255, 0, 0); // Regular instance
const blue = Color(0, 0, 255); // Constant instanceConstant constructors are useful for immutable configuration objects, predefined values, and optimizing memory usage.
Try it yourself
import 'difficulty.dart';
void main() {
// TODO: Create three constant difficulty presets using the const keyword:
// - easy: name 'Easy', 5 enemies, 5 lives
// - medium: name 'Medium', 10 enemies, 3 lives
// - hard: name 'Hard', 20 enemies, 1 life
// TODO: Call display() on each difficulty in order: easy, medium, hard
// TODO: Check if two const Difficulty('Easy', 5, 5) objects are identical
// using identical() and print the result
}
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