Passing parameters
- Flutter course
- Beginner
- Lesson 18/99
- 4 min
Learn to pass data to widgets via constructor parameters.
Passing data via constructor
Data is passed into a StatelessWidget through constructor parameters. Parameters are usually declared final because the widget is immutable. The required keyword forces non-nullable parameters to be supplied.
class Etiket extends StatelessWidget {
final String metin;
const Etiket({super.key, required this.metin});
@override
Widget build(BuildContext context) {
return Text(metin);
}
}final and required
final fields cannot be changed after the instance is created; this is the core of immutability. required forces named parameters to be supplied at the call site. Without required, a parameter becomes optional and may be null.
class Kart extends StatelessWidget {
final String baslik;
final String? altBaslik; // optional
const Kart({
super.key,
required this.baslik,
this.altBaslik,
});
}Practice Print parameter info
In main, print two lines with print: final sabit and required zorunlu.
Starter code
void main() {
// iki satır yazdır:
// final sabit
// required zorunlu
}Sample solution
void main() {
print('final sabit');
print('required zorunlu');
}Expected output
final sabit required zorunlu
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How is data passed to a StatelessWidget?
- Through setter methods
- Through global variables
- Through constructor parameters Correct answer
- By defining inside the build method
Explanation: Data is passed to a StatelessWidget via constructor parameters; stored as final fields.
2 Required parameter
const Etiket({
super.key,
____ this.metin,
});
const Etiket({
super.key,
required this.metin,
});
Explanation: required forces non-nullable named parameters to be given.
3 Parameter concepts
| Term | Meaning |
|---|---|
constructor |
Method creating a class instance |
final |
Immutable field |
required |
Forces a parameter to be given |
this.metin |
Assigns parameter to field |