3 types-
In Dart, you can use Required Positional Parameters to enforce that specific arguments must be provided when calling a function.
void main() {
minus(7, 2, 1);
}
int minus(int a, int b, int c) {
print(a - b - c);
}
Having many parameters makes things unclear, therefore in order to make the code easier to read and more streamlined, we've called Named Parameter. Arguments are now enclosed in a pair of curly brackets and given the name parameters. We must always include the parameter name when calling the function in order to pass this type of parameter. All of the data types must be made nullable, or must provide values or use required; in this instance, the parameters name are necessary; if we omit them, a compilation fault will occur.
main() {
showStudents(7, name: "sdf", age: 65, dob: "4/55");
}
void showStudents(int? id, {required String name, int? age = 55, String? dob}) {
// print("id: $id");
print(id ?? 3);
print("name: $name");
print("age $age");
print("dob $dob");
}
By enclosing your parameters inside square brackets, you can make them Optional Parameters. These parameters are now optional; if I don't pass them, the code will run without an error and return null. This time, I won't need to explicitly pass null for these parameters.
Additionally, you should note that if you make any of your parameters optional, they should also be nullable because the default value is null, or you can declare a default value.
void main() {
showStudents("sdf");
}
void showStudents(String name, [int? age, int? dob]) {
print("$name");
print(age ?? 55);
print("$dob");
}
Top comments (1)
+1 optional parameters