Search code examples
flutterdartrefactoringdry

DART: How to pass an argument to a method that needs to be a const


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?


Solution

  • 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,
        );
      }
    }