Reputation: 371
I'm refactoring a Flutter app for readability, and decided to reduce duplication by moving repeated calls to wrap a widget with Padding by extracting a method. The method looks like this:
Padding _wrapWithPadding(Widget widget, {double horizontal = 8.0, double vertical = 0.0}) {
return const Padding(padding:
EdgeInsets.symmetric(horizontal: horizontal, vertical: vertical),
child: widget);
}
The Dart compiler complains that horizontal, vertical, and widget arguments are not const on the call to the Padding constructor. I understand the problem, but surely there is a way to accomplish removing the duplication of creating a Padding element over and over again?
Is there someway to get the compiler to treat those values as const, or is there another way to accomplish my goal?
Upvotes: 3
Views: 1590
Reputation: 317
If you want the padding to be constant, you should make sure that its child is created by const construction. I don't suggest that.
But alternatively, you can use extension methods
extension WidgetExtension on Widget {
Padding addPadding({double horizontal = 8.0, double vertical = 0.0}) {
return Padding(
padding:
EdgeInsets.symmetric(horizontal: horizontal, vertical: vertical),
child: this);
}
}
Container().addPadding();
Upvotes: 1
Reputation: 277287
This is not feasible with a function.
You can, on the other hand, use a StatelessWidget
.
class MyPadding extends StatelessWidget {
const MyPadding(
this.widget, {
Key key,
this.horizontal,
this.vertical,
}) : super(key: key);
final Widget widget;
final double horizontal;
final double vertical;
@override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.symmetric(horizontal: horizontal ?? 8, vertical: vertical ?? .0),
child: widget,
);
}
}
Upvotes: 0