2024年7月2日 18:34

What are positional parameters in Flutter?

In Flutter (and the Dart language), positional parameters refer to parameters that are passed in the order they are declared within a function or constructor. These parameters must be passed in the order they are declared when calling the function, and are typically required unless marked as optional.

Consider the following function definition:

dart
void greet(String firstName, String lastName) { print("Hello, $firstName $lastName!"); }

In this function, firstName and lastName are positional parameters. When calling this function, you must provide both parameters in order, such as greet('John', 'Doe').

If you want certain positional parameters to be optional, you can define them using square brackets [ ], such as:

dart
void greet(String firstName, [String lastName]) { if (lastName == null) { print("Hello, $firstName!"); } else { print("Hello, $firstName $lastName!"); } }

In this modified version of the function, lastName is an optional positional parameter. You can call it with only one parameter, greet('John'), or with both parameters, greet('John', 'Doe').

标签:Flutter