Constructors are special methods that run when you create an object. They are primarily used to set up the initial values of the object fields.
1. The Generative Constructor
The standard constructor has the same name as the class. Dart provides a shorthand syntax this.field to simplify assignments.
Constructor Syntax
1class User {2 String username;3 int id;4 5 // Long way6 // User(String username, int id) {7 // this.username = username;8 // this.id = id;9 // }10 11 // Dart Shorthand (Preferred)12 User(this.username, this.id);13}14 15void main() {16 User u = User('decoder', 101);17 print(u.username);18}HintThe shorthand User(this.username, this.id) automatically assigns the arguments to the fields.
2. Named Parameters in Constructors
Just like functions, constructors can have named parameters. This is standard in Flutter.
Named Constructor Args
1class Button {2 String text;3 double width;4 5 // Named parameters with 'required'6 Button({required this.text, this.width = 100.0});7}8 9void main() {10 // Clear and readable11 Button btn = Button(12 text: 'Submit',13 width: 200.0,14 );15}HintThis style allows for optional parameters and default values, making object creation flexible.
3. Named Constructors
Dart does not support method overloading (multiple constructors with the same name). Instead, you define "Named Constructors".
Custom Constructors
1class Point {2 double x, y;3 4 Point(this.x, this.y); // Default5 6 // Named constructor7 Point.origin() {8 x = 0;9 y = 0;10 }11 12 // Another named constructor13 Point.fromJson(Map<String, dynamic> json) {14 x = json['x'];15 y = json['y'];16 }17}18 19void main() {20 var p1 = Point(10, 20);21 var p2 = Point.origin(); // x=0, y=022}HintPoint.origin and Point.fromJson are clear, descriptive ways to create instances.
Loot collected
Key takeaways- Use
this.fieldsyntax to write concise constructors. - Use named parameters (
{}) for readability, especially with many fields to initialize. - Use Named Constructors (
Class.name) to provide alternative ways to create an object. - A constructor always calls
super()implicitly unless you redirect it.
Side quests
Practice exercises
Exercise 1: Book Class
Create a Book class with title and author. Create a constructor that requires both.
Reveal solutionHide solution
1class Book { String title; String author; Book(this.title, this.author); }Exercise 2: Named Constructor
Add a named constructor Book.anonymous(title) that sets author to "Unknown".
Reveal solutionHide solution
1Book.anonymous(this.title) { author = 'Unknown'; }