What kinds of parameters exist in Dart (positional, optional, named) and how do you declare them?
Show answer — try answering out loud first
Dart has required positional parameters, optional positional parameters (inside []), and named parameters (inside {}). Named parameters are passed with name: value and are optional by default, unless you mark them with required. You can give default values to both optional and named parameters.
- Required positional: the usual ones. Order matters.
add(a, b). - Optional positional (
[ ]): you can leave them out. If they aren't provided, they arenull(or the default value you define). - Named (
{ }): you pass them by giving the name. They improve readability and don't depend on order. They are optional unless you userequired.
In Flutter almost everything uses named parameters (that's why you write Container(width: 100, height: 50)). On top of that, arrow functions (=>) are syntactic sugar for functions with a single expression.
// Required positional
int add(int a, int b) => a + b;
// Optional positional with a default value
String greet(String name, [String greeting = "Hello"]) {
return "$greeting, $name";
}
// Named: one required and one with a default value
String describe({required String name, int age = 0}) {
return "$name is $age years old";
}
void main() {
print(add(2, 3)); // 5
print(greet("Mike")); // "Hello, Mike"
print(greet("Mike", "Hey")); // "Hey, Mike"
print(describe(name: "Ana")); // "Ana is 0 years old"
print(describe(name: "Ana", age: 30)); // "Ana is 30 years old"
// The order of named parameters doesn't matter
print(describe(age: 25, name: "Luis")); // "Luis is 25 years old"
}
Forgetting required on a named parameter that has no default value and isn't nullable. With null safety, Dart forces your hand: a non-nullable named parameter with no default value has to be required, or it won't compile. Many juniors try to write String describe({String name}) and don't understand why it fails.
"Dart has required positional parameters, optional positional parameters that go inside square brackets, and named parameters that go inside curly braces and are passed as
name: value. Named parameters are optional by default, but if they're non-nullable and have no default value, you have to mark them withrequired. In Flutter almost everything uses named parameters because it makes the code much more readable, like in widget constructors."
Why doesn't this function compile, and how do you fix it?
String label({String text}) => text;
See answer
It doesn't compile because text is a non-nullable named parameter with no default value, and null safety requires it to be required. Possible fixes:
String label({required String text}) => text;String label({String text = ""}) => text;String label({String? text}) => text ?? "";