Flutter
Flexibility via parameters
Make the widget flexible via constructor parameters.
Constructor parameters
To make a custom widget flexible you take fields as constructor parameters. The required keyword marks a parameter as mandatory, while = value specifies a default. This way the same widget works with different data.
class Etiket extends StatelessWidget {
final String yazi;
final Color renk;
const Etiket({
super.key,
required this.yazi,
this.renk = const Color(0xFF000000),
});
@override
Widget build(BuildContext context) {
return Text(yazi, style: TextStyle(color: renk));
}
}
Default value
If you give a parameter a default value with = value, that value is used when the parameter is omitted at the call site. You cannot mark the same parameter with required; the two are mutually exclusive.
const Etiket({
super.key,
required this.yazi,
this.renk = const Color(0xFF000000), // default
});
So Etiket(yazi: 'Selam') yields a black label.
Exercise Write the Etiket widget
Define a StatelessWidget named Etiket. The final String yazi field should be required, and the final Color renk field should default to const Color(0xFF000000). The build method should return Text(yazi, style: TextStyle(color: renk)). Print 'hazir' in main.
Show example solution
import 'package:flutter/widgets.dart';
class Etiket extends StatelessWidget {
final String yazi;
final Color renk;
const Etiket({
super.key,
required this.yazi,
this.renk = const Color(0xFF000000),
});
@override
Widget build(BuildContext context) {
return Text(yazi, style: TextStyle(color: renk));
}
}
void main() {
print('hazir');
}
Test yourself
-
What does the required keyword specify?
- That the parameter is final
- That the parameter is mandatory
- That the parameter has a default value
- That the parameter is async
Show answer
That the parameter is mandatory — required marks a named parameter as mandatory to provide at the call site. async is a function behavior, final expresses field immutability, and a default value is given with =.
-
Mark a mandatory parameter
const Etiket({
super.key,
____ this.yazi,
this.renk = const Color(0xFF000000),
});
Show answer
const Etiket({
super.key,
required this.yazi,
this.renk = const Color(0xFF000000),
});
-
Parameter parts
- required
- Mandatory parameter
- = deger
- Default value
- this.yazi
- Binding a field to the constructor
- final
- Immutable field
Next lesson: Reusability