On this page13 sections
Lecture 027: Optional, Named & Default Parameters
| Day | 10: Functions & Parameters |
| Lecture | 027 of 057 |
| Estimated video length | 14 min |
| Target | Dart 3.12 |
| Level | Beginner |
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:
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. AliIf 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:
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.0With a default, the type doesn't need ?.
3. Named Parameters
Wrap them in curly braces. In the call, write name: value, in any order:
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 unknownNamed parameters are optional unless you say otherwise, and can have defaults too:
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: falseCompare 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:
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
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:
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
| Kind | Syntax | In the call | Left 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
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
Rs 1500
Rs 1499.50
$ 25.00
+Rs 300The 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
void sendEmail({required String to, required String subject}) {}
sendEmail(to: 'ali@mail.com');Error: Required named parameter 'subject' must be provided.2. A named parameter that can't be null, with no default
void createUser({String 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.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
void setVolume({int level = 50}) {}
setVolume(80);Error: Too many positional arguments: 0 allowed, but 1 found.Write setVolume(level: 80);.
4. Using [ ] and { } in the same function
void f([int a = 0], {int b = 0}) {}Error: Expected ')' before this.Choose one kind of optional parameter.
Practice Questions
- Write
void greet([String name = 'friend'])and show two ways to call it. - With
void box({int width = 1, int height = 1}), what's printed by a body that prints both, forbox(height: 5)? - Why does
void f({int count})not compile? Give two fixes. - Which is easier to read:
book('Ali', 2, true)orbook('Ali', nights: 2, breakfast: true)? - Can named arguments be passed in any order?
Practice Answers
greet();(prints the default) andgreet('Sara');.width= 1,height= 5.countwould benullwhen left out, butintcan't be null. Fix:{int count = 0}or{required int count}(or{int? count}).- The named version.
- Yes.
Key Takeaways
[ ]= optional positional;{ }= named (optional unlessrequired).- 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.