Using optional parameters as required in dart

Dart optional parameters with required annotation :

Optional parameters in a dart function are optional i.e. even if we don’t pass them to a function, the program will work. But, if you want to change one optional parameter to required, you can either change it directly to required or use the required annotation. The program will still work if you use the required annotation but it will show one warning.

Example of optional parameter :

Let’s create one console application using stagehand. Create one folder and run the below command to create one stagehand console app :

stagehand console-full

Check this tutorial if you are new to stagehand.

Run pub get to install the dependencies. Now, edit the bin/main.dart file as below :

printMessage(String param1, {String param2, String param3}) {
  print('param1 : $param1');
  print('param2 : $param2');
  print('param3 : $param3');
}

main() {
  printMessage("Hello", param2: "World", param3: "!!");
  printMessage("Hello");
}

Here, the parameters param2 and param3 are optional. You can run this program using dart as like below :

dart bin/main.dart

Now, to make param2 optional, do the following :

1. Import meta.dart :

import 'package:meta/meta.dart';

2. Add the required annotation before param2.

Final program :

import 'package:meta/meta.dart';

printMessage(String param1, { String param2, String param3}){
  print('param1 : $param1');
  print('param2 : $param2');
  print('param3 : $param3');
}

main() {
  printMessage("Hello", param2: "World", param3: "!!");
  printMessage("Hello");
}

The second printMessage will show one warning after this change that the parameter param2 is required.

Where is the color and why codevscolor ?

Long story short, I love paintings and I paint on weekends. We(me and my wife) have one Youtube channel. Below is a video that I did recently. If you love this please do subscribe to support us 😊