xxxxxxxxxx
void greet(String name, {String prefix = 'Hello'}) {
print('$prefix, $name!');
}
void main() {
greet('Alice'); // Output: Hello, Alice!
greet('Bob', prefix: 'Hi'); // Output: Hi, Bob!
}
xxxxxxxxxx
Curly brackets {} are used to specify optional, named parameters in Dart.
or use [] to specify optional parameters aswell
readFile(String name, {String mode, String charset = 'utf-8'}) {
// empty
}
Named parameters are referenced by name,
which means that they can be used during the function
invocation in an order different from the function declaration.
readFile('hello.dart','14');
readFile('hello.dart', mode: 'w+');
readFile('hello.dart', charset: 'iso8859-1');
readFile('hello.dart', charset: 'iso8859-1', mode: 'w+');
readFile('hello.dart', mode: 'w+', charset: 'iso8859-1');
readFile2(String name, [String? mode]) {
// empty
}
readFile2('hello.dart','w+');
readFile2('hello.dart');
xxxxxxxxxx
class TextInputWithIcon extends StatefulWidget {
final String iconPath;
final String placeHolder;
final Function(bool)? onFocusChange; // nullable and optional
const TextInputWithIcon(
{Key? key,
required this.iconPath, // non-nullable and required
this.placeHolder = "", // non-nullable but optional with a default value
this.onFocusChange, // nullable and optional
})
: super(key: key);
@override
_TextInputWithIconState createState() => _TextInputWithIconState();
}
https://levelup.gitconnected.com/3-types-of-dart-parameters-and-using-them-correctly-61d4204d53a5#69be
xxxxxxxxxx
Making a dynamic parameter optional
>> bind it to the class immediately after super.key e.g {super.key, this.optionalParameter}
>> declare it adding ? to it's type e.g final String? this.optionalParameter