Search⌘ K
AI Features

Optional Parameters

Explore how to create flexible Dart functions using optional parameters. Learn the difference between named and positional optional parameters, including nullable types and required named parameters. Understand how to call these functions to write clear and adaptable code that respects Dart's null safety principles.

When defining functions, we often want to make certain inputs optional so the caller does not have to provide every single argument. Dart provides two ways to do this: named parameters and positional parameters.

A function can have two types of parameters: required and optional. The required parameters are listed first, followed by any optional parameters. We can use either optional named parameters or optional positional parameters, but we cannot mix both optional styles in the same function declaration.

Named parameters

In a function, we declare optional named parameters by wrapping them in curly braces ({}). Due to Dart's Sound Null Safety rules, omitted optional parameters default to null. Therefore, we must explicitly mark them as nullable using a question mark (such as String?).

Syntax for named parameters:

returnType functionName(requiredParam, {type? optionalParam1, type? optionalParam2}) {
The syntax blueprint for declaring named parameters

When calling a function with named parameters, we explicitly state the parameter name followed by a colon and the value. Because we ...