Flutter
Composition
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,
);
}
}
Exercise 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.
Show example 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');
}
Test yourself
-
What does composition enable?
- Building complex interfaces with nested widgets
- Writing data to a database
- Sending an HTTP request
- Decoding a JSON string
Show answer
Building complex interfaces with nested widgets — Composition enables building UIs by nesting widgets. Database, HTTP, and JSON decoding are unrelated to composition; they belong to different layers.
-
Pass the child parameter
return Padding(
padding: const EdgeInsets.all(8),
____,
);
Show answer
return Padding(
padding: const EdgeInsets.all(8),
child: child,
);
-
Composition parts
- 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
Next lesson: Flexibility via parameters