Flutter
Component library
Build a reusable component library.
What is a component library?
A component library is a collection of reusable widgets. It gathers frequently used building blocks like buttons, cards and inputs into a single package. It is the application side of the design system and ensures a consistent look.
class PrimaryButton extends StatelessWidget {
final String label;
final VoidCallback onPressed;
const PrimaryButton({
super.key,
required this.label,
required this.onPressed,
});
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: onPressed,
child: Text(label),
);
}
}
Flexibility through parameters
Components become flexible through parameters. But instead of exposing every possibility, you expose only the most common variations as parameters. You simplify usage by providing default values.
class AppCard extends StatelessWidget {
final Widget child;
final EdgeInsets? padding;
final Color? color;
const AppCard({
super.key,
required this.child,
this.padding,
this.color,
});
@override
Widget build(BuildContext context) {
return Container(
padding: padding ?? const EdgeInsets.all(16),
decoration: BoxDecoration(
color: color,
borderRadius: BorderRadius.circular(8),
),
child: child,
);
}
}
Exercise Write a custom button component
Write a StatelessWidget named AppButton. It takes label (String) and onPressed (VoidCallback) parameters, both required. The build method returns an ElevatedButton whose child is Text(label). In main, create an AppButton and print its label.
Show example solution
import 'package:flutter/material.dart';
class AppButton extends StatelessWidget {
final String label;
final VoidCallback onPressed;
const AppButton({
super.key,
required this.label,
required this.onPressed,
});
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: onPressed,
child: Text(label),
);
}
}
void main() {
final btn = AppButton(
label: 'Kaydet',
onPressed: () {},
);
print(btn.label);
}
Test yourself
-
What is the main benefit of a component library?
- Reduce app size
- Ensure consistency and reduce code duplication
- Speed up network requests
- Eliminate compile time
Show answer
Ensure consistency and reduce code duplication — A component library gathers repeated UI structures in one place; this provides both a consistent look and less code duplication.
-
Required parameter
class AppCard extends StatelessWidget {
final Widget child;
const AppCard({super.key, ____});
Show answer
class AppCard extends StatelessWidget {
final Widget child;
const AppCard({super.key, required this.child});
-
Component parts
- StatelessWidget
- Stateless component base
- required
- Required parameter marker
- super.key
- Forwards key to parent
- VoidCallback
- Tap callback type
Next lesson: Theme switching