On this page13 sections
  1. Prerequisites
  2. Learning Objectives
  3. 1. Optional Positional Parameters
  4. 2. Default Values
  5. 3. Named Parameters
  6. 4. Required Named Parameters
  7. 5. Mixing Positional and Named
  8. 6. Summary
  9. Code Examples
  10. Common Beginner Mistakes
  11. Practice Questions
  12. Practice Answers
  13. Key Takeaways

Lecture 027: Optional, Named & Default Parameters

Day10: Functions & Parameters
Lecture027 of 057
Estimated video length14 min
TargetDart 3.12
LevelBeginner

Not every value is always needed: a title before a name, a custom tax rate, a gift-wrap option. Dart lets parameters be optional, have default values, and be passed by name, so calls stay short and readable. Flutter uses named parameters everywhere.

Contents

Prerequisites · Objectives · Lesson · Code Examples · Common Mistakes · Practice Questions · Answers · Takeaways


Prerequisites

Lectures 010 (null safety) and 025–026 (functions and positional parameters).


Learning Objectives

  • Make positional parameters optional with [ ]
  • Give parameters default values
  • Write and call named parameters with { }
  • Make a named parameter required with required
  • Combine positional and named parameters

1. Optional Positional Parameters

Wrap them in square brackets. They must come after the required ones:

dart
String greet(String name, [String? title]) {
  if (title != null) return 'Hello, $title $name';
  return 'Hello, $name';
}

print(greet('Ali'));          // Hello, Ali
print(greet('Ali', 'Dr.'));   // Hello, Dr. Ali

If it's left out, title is null, so its type must be nullable (String?).

2. Default Values

Give a parameter a value to use when it's left out:

dart
double price(double amount, [double tax = 0.05]) => amount + amount * tax;

print(price(1000));         // 1050.0 (default 5% tax)
print(price(1000, 0.17));   // 1170.0

With a default, the type doesn't need ?.

3. Named Parameters

Wrap them in curly braces. In the call, write name: value, in any order:

dart
void createUser({String? name, int? age}) {
  print('User: ${name ?? 'unknown'}, age ${age ?? 'unknown'}');
}

createUser(name: 'Sara', age: 21);   // User: Sara, age 21
createUser(age: 30);                 // User: unknown, age 30
createUser();                        // User: unknown, age unknown

Named parameters are optional unless you say otherwise, and can have defaults too:

dart
void setVolume({int level = 50, bool muted = false}) {
  print('Volume $level, muted: $muted');
}

setVolume();              // Volume 50, muted: false
setVolume(muted: true);   // Volume 50, muted: true
setVolume(level: 80);     // Volume 80, muted: false

Compare setVolume(true, 80), which is a mystery, with setVolume(muted: true, level: 80), which explains itself.

4. Required Named Parameters

Add required when a named parameter must always be passed:

dart
void sendEmail({required String to, required String subject, String body = ''}) {
  print('To: $to | Subject: $subject | Body: ${body.isEmpty ? '(empty)' : body}');
}

sendEmail(to: 'ali@mail.com', subject: 'Hello');
sendEmail(subject: 'Report', to: 'boss@mail.com', body: 'Attached.');

Output

code
To: ali@mail.com | Subject: Hello | Body: (empty)
To: boss@mail.com | Subject: Report | Body: Attached.

5. Mixing Positional and Named

Required positional parameters come first, then the named ones:

dart
void order(String item, {int quantity = 1, bool giftWrap = false}) {
  print('$quantity × $item${giftWrap ? ' (gift wrapped)' : ''}');
}

order('Book');                               // 1 × Book
order('Pen', quantity: 5);                   // 5 × Pen
order('Watch', giftWrap: true, quantity: 2); // 2 × Watch (gift wrapped)

6. Summary

KindSyntaxIn the callLeft out →
required positional(int a)f(1)error
optional positional([int? a])f() or f(1)null
optional positional + default([int a = 0])f() or f(1)0
named({int? a})f(a: 1)null
named + default({int a = 0})f(a: 1)0
required named({required int a})f(a: 1)error

A function can have optional positional or named parameters, but not both.


Code Examples

Example 1: Formatting Prices

dart
String formatPrice(
  double amount, {
  String currency = 'Rs',
  int decimals = 0,
  bool showPlus = false,
}) {
  var text = amount.toStringAsFixed(decimals);
  var sign = showPlus && amount > 0 ? '+' : '';
  return '$sign$currency $text';
}

void main() {
  print(formatPrice(1500));
  print(formatPrice(1499.5, decimals: 2));
  print(formatPrice(25, currency: '\$', decimals: 2));
  print(formatPrice(300, showPlus: true));
}

Output

code
Rs 1500
Rs 1499.50
$ 25.00
+Rs 300

The amount is always needed, so it's positional. Everything else has a sensible default and is named, so each call only mentions what's different.


Common Beginner Mistakes

1. Leaving out a required named parameter

dart
void sendEmail({required String to, required String subject}) {}

sendEmail(to: 'ali@mail.com');
code
Error: Required named parameter 'subject' must be provided.

2. A named parameter that can't be null, with no default

dart
void createUser({String 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.

Named parameters are optional, so a left-out one would be null. Use String?, give a default, or add required.

3. Passing a named parameter without its name

dart
void setVolume({int level = 50}) {}

setVolume(80);
code
Error: Too many positional arguments: 0 allowed, but 1 found.

Write setVolume(level: 80);.

4. Using [ ] and { } in the same function

dart
void f([int a = 0], {int b = 0}) {}
code
Error: Expected ')' before this.

Choose one kind of optional parameter.


Practice Questions

  1. Write void greet([String name = 'friend']) and show two ways to call it.
  2. With void box({int width = 1, int height = 1}), what's printed by a body that prints both, for box(height: 5)?
  3. Why does void f({int count}) not compile? Give two fixes.
  4. Which is easier to read: book('Ali', 2, true) or book('Ali', nights: 2, breakfast: true)?
  5. Can named arguments be passed in any order?

Practice Answers

  1. greet(); (prints the default) and greet('Sara');.
  2. width = 1, height = 5.
  3. count would be null when left out, but int can't be null. Fix: {int count = 0} or {required int count} (or {int? count}).
  4. The named version.
  5. Yes.

Key Takeaways

  • [ ] = optional positional; { } = named (optional unless required).
  • Defaults (= value) fill in missing arguments.
  • Left-out optional parameters without defaults are null, so their type needs ?.
  • Named arguments are written name: value, in any order.
  • Required positional first, then optional or named; never [ ] and { } together.