What is the difference between named and positional parameters in Dart?

CodeWithFlutter
2 Min Read

In Dart, there are two types of parameters that can be passed to a function: named parameters and positional parameters.

Positional parameters are defined by their position in the function signature, and they are passed to the function in the order they are defined. For example:

void printInfo(String name, int age) {
  print('Name: $name, Age: $age');
}

void main() {
  printInfo('John', 30);
}

In this example, the printInfo function takes two positional parameters: name and age. When we call printInfo, we pass the values 'John' and 30 to the function in the same order as they are defined.

Named parameters, on the other hand, are defined with a name and an optional default value, and they can be passed to the function in any order, as long as the names are specified. Named parameters are defined using curly braces {} in the function signature:

void printInfo({String name, int age}) {
  print('Name: $name, Age: $age');
}

void main() {
  printInfo(age: 30, name: 'John');
}

In this example, the printInfo function takes two named parameters: name and age. When we call printInfo, we pass the values 'John' and 30 to the function by specifying the names of the parameters. This allows us to pass the parameters in any order we want.

So the main difference between named and positional parameters is that positional parameters are passed to the function in the order they are defined, while named parameters can be passed in any order, as long as the names are specified.

Share this Article
Leave a comment