On this page12 sections
  1. Prerequisites
  2. Learning Objectives
  3. 1. Required Positional
  4. 2. Optional Positional
  5. 3. Named (Optional, Required, Default)
  6. 4. Mixing Positional and Named
  7. 5. final Fields
  8. Code Examples
  9. Common Beginner Mistakes
  10. Practice Questions
  11. Practice Answers
  12. Key Takeaways

Lecture 032: Constructor Parameters

Day11: Classes, Objects & Constructors
Lecture032 of 057
Estimated video length14 min
TargetDart 3.12
LevelBeginner

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.

dart
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 pages

2. Optional Positional

In square brackets. A left-out value is null (so the field needs ?) or uses its default:

dart
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 128GB

3. Named (Optional, Required, Default)

In curly braces, passed as name: value in any order:

dart
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: true
  • required this.name must be passed.
  • this.email is optional, so it's null when left out (the field is String?).
  • this.isAdmin = false is optional, with a default.

4. Mixing Positional and Named

dart
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);        // 1

5. final Fields

Mark a field final when it should never change after the object is created. The constructor still sets it:

dart
class Appointment {
  final String patient;
  ...
}

Flutter widgets are built this way: final fields and named constructor parameters.

KindConstructor syntaxField type when optional
required positionalC(this.a)T
optional positionalC([this.a]) / C([this.a = x])T? / T
required namedC({required this.a})T
optional namedC({this.a}) / C({this.a = x})T? / T

Code Examples

Example 1: Doctor Appointments

dart
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

code
Hamza with Dr. Ayesha at 10:30, at the clinic
Zara with Dr. Bilal at 14:00, online
  Notes: Follow-up on test results

The 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

dart
var u = User();
code
Error: Required named parameter 'name' must be provided.

2. An optional named parameter for a non-nullable field

dart
class User {
  String name;
  User({this.name});
}
code
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

dart
var u = User('Ali');
u.name = 'Sara';   // name is final
code
Error: The setter 'name' isn't defined for the type 'User'.

final fields are set once, by the constructor.


Practice Questions

  1. Write a class Movie with final String title and final int year, both required named parameters.
  2. With Phone(this.brand, [this.model, this.storageGb = 64]), what is storageGb for Phone('Nokia')?
  3. Why must email be String? in User({this.email})?
  4. Rewrite Order('Pen', 5) so the quantity is named.
  5. What happens when you assign to a final field after creating the object?

Practice Answers

dart
class Movie {
  final String title;
  final int year;
  Movie({required this.title, required this.year});
}
  1. 64, the default.
  2. It's optional with no default, so it's null when left out.
  3. Constructor Order(this.item, {this.quantity = 1}), called as Order('Pen', quantity: 5).
  4. A compile error. final fields can't be changed.

Key Takeaways

  • Constructor parameters work like function parameters, using this.field.
  • [this.a] = optional positional; {this.a} = named; add required or = default as needed.
  • Optional parameters without defaults need nullable fields (T?).
  • final fields are set once by the constructor and never change.
  • Named + required + final is the Flutter style.