Optional Parameters in Dart

<Blake†Codez />
2 min readJan 8, 2023

In Dart, optional parameters can be defined by using brackets [ ] to let the compiler know these parameters are optional.

Here [String? optional] is an optional parameter. Also note, that whenever you have an optional parameter, it always can be null.

myFunction can now be executed properly by only passing in 1 parameter value. The second, optional, is completely optional of course an it’s value will be null if nothing is passed in.

void main() {
myFunction('hello');
// Value: hello
// Optional: null
}

void myFunction(String value, [String? optional]) {
print('Value: $value');
print('Optional: $optional');
}

We can also specify another way of declaring an optional parameter using an optional named parameter. Named parameters are either required, meaning they must have values, or not required, meaning they are optional.

To declare a named parameter is done simply like so:

// number here is optional and is also marked nullable.
// text is of course required, and cannot ever be null since it is declared as String
void myNamedParameterFunction({ required String text, int? number }) {
print('Text: $text');
print('Number: $number');
}

void main() {
myNamedParameterFunction(text: 'hello');
}

Above, text is declared as a name parameter with the String value of ‘hello’. Number of course is completely optional, because it can be null.

If we wanted to, we could declare number to have a default value so it will never be null.

// Here number is optional but will also never be null.
// It will always default to 0;
void myNamedParameterFunction({ required String text, int number = 0 }) {
print('Text: $text');
print('Number: $number');
}

Thanks for reading! 😎👋🏽

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

<Blake†Codez />
<Blake†Codez />

Written by <Blake†Codez />

I’m a Software Engineering student in Redding, Ca. Love all things Computer Science related, love for journalism, Jesus Christ, and team collaboration projects.

No responses yet

What are your thoughts?