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

798

Solution 1

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

Solution 2

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();
Share:
798
beer geek
Author by

beer geek

Updated on December 18, 2022

Comments

  • beer geek
    beer geek over 1 year

    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?

    • Admin
      Admin about 4 years
      it looks not clever, you're trying to replace one widget with another function...no profit...and of course you have to remove const keyword
    • Rémi Rousselet
      Rémi Rousselet about 4 years
      What you're trying to do is simply not possible.