On this page12 sections
Lecture 032: Constructor Parameters
| Day | 11: Classes, Objects & Constructors |
| Lecture | 032 of 057 |
| Estimated video length | 14 min |
| Target | Dart 3.12 |
| Level | Beginner |
Constructors take parameters exactly like functions do: required, positional, optional, named, with defaults. Choosing the right kind makes objects easy and safe to create. This is the style every Flutter widget uses.
Contents
Prerequisites · Objectives · Lesson · Code Examples · Common Mistakes · Practice Questions · Answers · Takeaways
Prerequisites
Lectures 026–027 (parameters) and 031 (constructors).
Learning Objectives
- Use required positional constructor parameters
- Make constructor parameters optional, with
[ ] - Use named constructor parameters, with
{ } - Make named parameters required, and give defaults
- Make fields unchangeable with
final
1. Required Positional
The simplest kind: every value must be passed, in order.
class Book {
String title;
String author;
int pages;
Book(this.title, this.author, this.pages);
}
var b = Book('Dune', 'Frank Herbert', 412);
print('${b.title} by ${b.author}, ${b.pages} pages');
// Dune by Frank Herbert, 412 pages2. Optional Positional
In square brackets. A left-out value is null (so the field needs ?) or uses its default:
class Phone {
String brand;
String? model;
int storageGb;
Phone(this.brand, [this.model, this.storageGb = 64]);
}
var p1 = Phone('Samsung');
var p2 = Phone('Apple', 'iPhone 15', 128);
print('${p1.brand} ${p1.model} ${p1.storageGb}GB'); // Samsung null 64GB
print('${p2.brand} ${p2.model} ${p2.storageGb}GB'); // Apple iPhone 15 128GB3. Named (Optional, Required, Default)
In curly braces, passed as name: value in any order:
class User {
String name;
String? email;
bool isAdmin;
User({required this.name, this.email, this.isAdmin = false});
}
var u1 = User(name: 'Sara');
var u2 = User(email: 'ali@mail.com', name: 'Ali', isAdmin: true);
print('${u1.name} ${u1.email} admin: ${u1.isAdmin}'); // Sara null admin: false
print('${u2.name} ${u2.email} admin: ${u2.isAdmin}'); // Ali ali@mail.com admin: truerequired this.namemust be passed.this.emailis optional, so it'snullwhen left out (the field isString?).this.isAdmin = falseis optional, with a default.
4. Mixing Positional and Named
class Order {
String item;
int quantity;
Order(this.item, {this.quantity = 1});
}
var o = Order('Pen', quantity: 5);
print('${o.quantity} × ${o.item}'); // 5 × Pen
print(Order('Book').quantity); // 15. final Fields
Mark a field final when it should never change after the object is created. The constructor
still sets it:
class Appointment {
final String patient;
...
}Flutter widgets are built this way: final fields and named constructor parameters.
| Kind | Constructor syntax | Field type when optional |
|---|---|---|
| required positional | C(this.a) | T |
| optional positional | C([this.a]) / C([this.a = x]) | T? / T |
| required named | C({required this.a}) | T |
| optional named | C({this.a}) / C({this.a = x}) | T? / T |
Code Examples
Example 1: Doctor Appointments
class Appointment {
final String patient;
final String doctor;
final String time;
final bool isOnline;
final String? notes;
Appointment({
required this.patient,
required this.doctor,
required this.time,
this.isOnline = false,
this.notes,
});
void confirm() {
var where = isOnline ? 'online' : 'at the clinic';
print('$patient with $doctor at $time, $where');
if (notes != null) print(' Notes: $notes');
}
}
void main() {
Appointment(patient: 'Hamza', doctor: 'Dr. Ayesha', time: '10:30').confirm();
Appointment(
patient: 'Zara',
doctor: 'Dr. Bilal',
time: '14:00',
isOnline: true,
notes: 'Follow-up on test results',
).confirm();
}Output
Hamza with Dr. Ayesha at 10:30, at the clinic
Zara with Dr. Bilal at 14:00, online
Notes: Follow-up on test resultsThe three must-have details are required; the extras are optional. Every call reads like a
sentence, and the trailing commas keep long calls tidy.
Common Beginner Mistakes
1. Leaving out a required named parameter
var u = User();Error: Required named parameter 'name' must be provided.2. An optional named parameter for a non-nullable field
class User {
String name;
User({this.name});
}Error: The parameter 'name' can't have a value of 'null' because of its type 'String', but the implicit default value is 'null'.
Try adding either an explicit non-'null' default value or the 'required' modifier.Add required, give a default, or make the field String?.
3. Changing a final field
var u = User('Ali');
u.name = 'Sara'; // name is finalError: The setter 'name' isn't defined for the type 'User'.final fields are set once, by the constructor.
Practice Questions
- Write a class
Moviewithfinal String titleandfinal int year, both required named parameters. - With
Phone(this.brand, [this.model, this.storageGb = 64]), what isstorageGbforPhone('Nokia')? - Why must
emailbeString?inUser({this.email})? - Rewrite
Order('Pen', 5)so the quantity is named. - What happens when you assign to a
finalfield after creating the object?
Practice Answers
class Movie {
final String title;
final int year;
Movie({required this.title, required this.year});
}64, the default.- It's optional with no default, so it's
nullwhen left out. - Constructor
Order(this.item, {this.quantity = 1}), called asOrder('Pen', quantity: 5). - A compile error.
finalfields can't be changed.
Key Takeaways
- Constructor parameters work like function parameters, using
this.field. [this.a]= optional positional;{this.a}= named; addrequiredor= defaultas needed.- Optional parameters without defaults need nullable fields (
T?). finalfields are set once by the constructor and never change.- Named +
required+finalis the Flutter style.