MonkeyMatt

Virtual Driver – Race Driver – Developer

Understanding Method Parameters in Dart

Method parameters in Dart are written differently to other languages I’m familiar with. After getting myself confused multiple times I’m writing this as a reference for my future self and anyone else who might be in the same position as me.

Examples you can play with: https://dartpad.dev/df02fd4952b91e85c2ec08e7d97f289e

Standard Parameters

int standardParams(int param1, String param2) {
  ...
}

void main() {
  var result = standardParams(3, '2');
  ...
}Code language: Dart (dart)

Each parameter defined this way is required when calling the method and must be specified in that order.

Can’t have a default value.

Named Parameters

int namedParams({required int param1, String? param2 = '1', double? param2}) {
  ...
}

void main() {
  var result = namedParams(param1: 3, param2: '2');
  ...
}Code language: Dart (dart)

Are surrounded in {}. Must be after any standard parameters. Must use the parameter name when the method is called. Can be used in any order.

Must either be nullable, use the required keyword, or have a default value.
(if it’s nullable without a default value the value when nothing is supplied will be null)

NOTE: Flutter widget constructors use only named parameters

Optional Positional Parameters

int optionalParams([int? param1, String param2 = '1']) {
  ...
}

void main() {
  var result = optionalParams(3);
  ...
}Code language: Dart (dart)

Are surrounded in []. Must be after any standard parameters. Aren’t required when calling but must be in the correct order.

Must either be nullable or have a default value.
(if it’s nullable without a default value the value when nothing is supplied will be null)

NOTE: You can’t have both named and optional positional parameters in the same method


Definitions

Required: Must be supplied when calling the method

Optional: Doesn’t need to be supplied when calling the method (will default to a specified value or null)

Positional: Must be supplied in the correct order when calling the method

Named: Must include the parameter name when calling the method

Standard Parameters are Required + Positional
Named Parameters are either Required or Optional + Named
Optional Positional Parameters are Optional + Positional (who would have guessed it)


Play around with these examples to test the limitations yourself: https://dartpad.dev/df02fd4952b91e85c2ec08e7d97f289e

Also worth following the official guidelines (e.g. use named params for booleans): https://dart.dev/guides/language/effective-dart/design#avoid-positional-boolean-parameters

References

Official explanation (didn’t explain it clearly enough for me): https://dart.dev/guides/language/language-tour#parameters

A great stack overflow answer explaining it: https://stackoverflow.com/a/55866881/8023278