Saturday, August 3, 2024

Flutter Dart Position and Named Arguments

 Deep Dive: Position & Named Arguments

In the previous lecture, you learned about "positional" and "named" arguments / parameters.

In general, function parameters / arguments (the term is used interchangeably here) are a key concept.

You use arguments to pass values into a function. The function may then use these parameter values to work with them - e.g., to display them on the screen, use them in a calculation or send them to another function.

In Dart (and therefore Flutter, since it uses Dart), you have two kinds of parameters you can accept in functions:

  • Positional: The position of an argument determines which parameter receives the value

  • Named: The name of an argument determines which parameter receives the value

Besides the different usage, there's one very important difference between positional and named arguments: By default, positional parameters are required and must not be omitted - on the other hand, named arguments are optional and can be omitted.

In the example above, when using named parameters, you could call add() like this:

or

When using positional parameters, calling add() like this would be invalid and hence cause an error!

You can change these behaviors, though. You can make positional arguments optional and named arguments required.

Positional arguments can be made optional by wrapping them with square brackets ([]):

Once a parameter is optional, you can also assign a default value to it - this value would be used if no value is provided for the argument:

Default values can also be assigned to named parameters - which are optional by default:

You can also make named parameters required by using the built-in required keyword:

You will, of course, see these different use-cases in action throughout the course.

No comments:

Post a Comment