Composition
- Flutter course
- Intermediate
- Lesson 72/99
- 4 min
Compose widgets by nesting them.
What is composition?
Composition is nesting widgets to build more complex interfaces. A widget's child parameter takes another widget, so the widget tree branches. This is the core philosophy of building UIs in Flutter.
class Cerceve extends StatelessWidget {
final Widget child;
const Cerceve({super.key, required this.child});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8),
child: child,
);
}
}This widget wraps its child in a Padding.
The child parameter
Many Flutter widgets take a child parameter that accepts a single widget. Some widgets like Column and Row take a list named children. Adding child as a parameter to your own widget turns it into a flexible wrapper.
class Cerceve extends StatelessWidget {
final Widget child;
const Cerceve({super.key, required this.child});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(12),
child: child,
);
}
}Practice Write the Cerceve widget
Define a StatelessWidget named Cerceve. It should have a final Widget child field added to the constructor as required. The build method should return a Padding with padding set to EdgeInsets.all(8) and child set to the incoming child. Print 'hazir' in main.
Starter code
import 'package:flutter/widgets.dart';
// Cerceve StatelessWidget tanımla
// final Widget child alanı olsun, required ile kurucuya ekle
// build metodu Padding döndürsün
// padding EdgeInsets.all(8), child gelen child olsun
void main() {
// 'hazir' yazdır
}Sample solution
import 'package:flutter/widgets.dart';
class Cerceve extends StatelessWidget {
final Widget child;
const Cerceve({super.key, required this.child});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8),
child: child,
);
}
}
void main() {
print('hazir');
}Expected output
hazir
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does composition enable?
- Building complex interfaces with nested widgets Correct answer
- Writing data to a database
- Sending an HTTP request
- Decoding a JSON string
Explanation: Composition enables building UIs by nesting widgets. Database, HTTP, and JSON decoding are unrelated to composition; they belong to different layers.
2 Pass the child parameter
return Padding(
padding: const EdgeInsets.all(8),
____,
);
return Padding(
padding: const EdgeInsets.all(8),
child: child,
);
Explanation: Padding takes a child parameter; children expects a list, and widget and body are not Padding's parameter names.
3 Composition parts
| Term | Meaning |
|---|---|
child |
Takes a single widget |
children |
Takes a list of widgets |
Padding |
Wrapper that adds inner spacing |
iç içe geçme |
Widget tree branching |