Dart Optional Parameters

Summary: in this tutorial, you’ll learn about Dart optional parameters and how to use them to make the functions more flexible.

Introduction to Dart optional parameters

The following defines the greet() function that accepts name and title and returns a greeting message:

String greet(String name, String title) {
  return 'Hello $title $name!';
}Code language: Dart (dart)

When calling the greet() function, you need to pass two arguments like this:

String greet(String name, String title) {
  return 'Hello $title $name!';
}

void main() {
  print(greet('John', 'Professor'));
}Code language: Dart (dart)

Output:

Hello Professor John!Code language: Dart (dart)

However, not everyone has a title. Therefore, the title parameter should be optional. To make a parameter optional, you use a square bracket. For example:

String greet(String name, [String title = '']) {
  if (title.isEmpty) {
    return 'Hello $name';
  }
  return 'Hello $title $name!';
}Code language: Dart (dart)

In this example, we use square brackets to make the title parameter optional. Also, we assign a default value to the title parameter.

Inside the function body, we return the corresponding greeting message based on whether the title is empty or not.

When calling the greet() function, you can omit the title if the person doesn’t have it like the following example:

String greet(String name, [String title = '']) {
  if (title.isEmpty) {
    return 'Hello $name';
  }
  return 'Hello $title $name!';
}

void main() {
  print(greet('John'));
}Code language: Dart (dart)

Or you can pass the title to the greet() function:

String greet(String name, [String title = '']) {
  if (title.isEmpty) {
    return 'Hello $name';
  }
  return 'Hello $title $name!';
}

void main() {
  print(greet('John'));
  print(greet('Alice', 'Professor'));
}Code language: Dart (dart)

It’s important to notice that Dart requires the optional parameters to appear last in the parameter list. Also, a function can have multiple optional parameters.

Summary

  • Use the square brackets [] to make one or more parameters optional.
  • Specify a default value for the optional parameters.
Was this tutorial helpful ?