Named Constructors
Part of the Object Oriented Programming section of Coddy's Dart journey — lesson 11 of 110.
Named constructors allow you to create multiple constructors for a class, each with a descriptive name that clarifies its purpose. This is especially useful when you need different ways to initialize an object.
The syntax uses the class name followed by a dot and the constructor name:
class Point {
int x;
int y;
// Regular constructor
Point(this.x, this.y);
// Named constructor for origin point
Point.origin() : x = 0, y = 0;
// Named constructor from a single value
Point.diagonal(int value) : x = value, y = value;
}Each named constructor provides a clear, readable way to create objects:
Point p1 = Point(3, 5);
Point p2 = Point.origin();
Point p3 = Point.diagonal(10);
print('p1: (${p1.x}, ${p1.y})'); // p1: (3, 5)
print('p2: (${p2.x}, ${p2.y})'); // p2: (0, 0)
print('p3: (${p3.x}, ${p3.y})'); // p3: (10, 10)Named constructors make your code more expressive. Instead of guessing what Point(0, 0) means, Point.origin() immediately communicates the intent. This pattern is common in Dart libraries and helps create self-documenting code.
Challenge
EasyLet's build a temperature converter that showcases the power of named constructors. You'll create a Temperature class that can be initialized in different ways depending on the unit you're starting with.
You'll organize your code into two files:
temperature.dart: Define aTemperatureclass with adouble celsiusinstance variable. Your class should provide three ways to create a temperature:- A regular constructor
Temperature(this.celsius)that takes a Celsius value directly - A named constructor
Temperature.fromFahrenheitthat accepts a Fahrenheit value and converts it to Celsius using the formula:(fahrenheit - 32) * 5 / 9 - A named constructor
Temperature.freezing()that creates a temperature at the freezing point (0 degrees Celsius)
display()method that prints:[celsius]C- A regular constructor
main.dart: Import your temperature class and create three temperature objects:- One using the regular constructor with
25.0 - One using
fromFahrenheitwith98.6 - One using
freezing()
display()on each temperature in the order listed above.- One using the regular constructor with
Expected output format:
25.0C
37.0C
0.0CCheat sheet
Named constructors allow you to create multiple constructors for a class with descriptive names that clarify their purpose.
The syntax uses the class name followed by a dot and the constructor name:
class Point {
int x;
int y;
// Regular constructor
Point(this.x, this.y);
// Named constructor for origin point
Point.origin() : x = 0, y = 0;
// Named constructor from a single value
Point.diagonal(int value) : x = value, y = value;
}Using named constructors:
Point p1 = Point(3, 5);
Point p2 = Point.origin();
Point p3 = Point.diagonal(10);
print('p1: (${p1.x}, ${p1.y})'); // p1: (3, 5)
print('p2: (${p2.x}, ${p2.y})'); // p2: (0, 0)
print('p3: (${p3.x}, ${p3.y})'); // p3: (10, 10)Named constructors make code more expressive and self-documenting by clearly communicating intent.
Try it yourself
import 'temperature.dart';
void main() {
// TODO: Create a Temperature using the regular constructor with 25.0
// TODO: Create a Temperature using fromFahrenheit with 98.6
// TODO: Create a Temperature using freezing()
// TODO: Call display() on each temperature 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