6

This is what I want to implement:

void fun({
  bool Function(int i) predicate = (i) => false,
}) {
  // do something with 'predicate(something)'
}

But I am getting the error:

The default value of an optional parameter must be constant.dart(non_constant_default_value).

I was able to get arround this error with the following:

bool falsePredicate(int i) => false;

void fun({
  bool Function(int i) predicate = falsePredicate,
}) {
  // do something with 'predicate(something)'
}

But now the question becomes, why can't I directly create a default function value as in the first set of code? There seems to be no difference between the first and the second cases. How is the function given in the first approach not constant?

Midhunraj R Pillai
  • 484
  • 1
  • 3
  • 16
  • 1
    It sounds like a feature people want, and one that ought to be possible: https://github.com/dart-lang/language/issues/1048 – Noah Apr 18 '21 at 03:35
  • Another alternative is to do [the typical approach of taking a `null` default](https://stackoverflow.com/q/56481645/): `void fun({bool Function(int i)? predicate}) { predicate ??= (i) => false; ... }`. – jamesdlin Apr 18 '21 at 05:35
  • In case of the alternate soultion, the method needs to be `static`. Does it really work without being static? – Sisir Apr 18 '21 at 09:02

1 Answers1

2

As @Noah has pointed to the git discussion, the dart language has this missing piece of compile-time constant functions, which eventually leads to this problem.

Check this post: https://github.com/dart-lang/language/issues/1048

As the post shows, the issue has been raised in mid-2012 and now it's been 8+ years. So the hopes of this being available in the near feature is very less.

However few alternative solutions till then:

Option 1 (separate method):

class ServiceProvider {
    static bool falsePredicate(int i) => false;
    
    void fun({
      bool Function(int i) predicate = falsePredicate,
    }) {
      // do something with 'predicate(something)'
    }
}

Option 2 (Null checking while using the predicate)

class ServiceProvider {
    void fun({
      bool Function(int i)? predicate,
    }) {
        int val = 55; // for demonstration
        predicate?.call(val); // Call only if the predicate is non-null
    }
}

Option 3 (Only for class constructors)

class ServiceProvider {
    final bool Function(int i) _predicate;
  
    ServiceProvider ({bool Function(int i)? predicate})
       : _predicate = predicate ?? ((i) => false);
  
    void fun() {
       int val = 55;
       _predicate(5); // No null check is needed. The predicate is always non-null
    }
}
Sisir
  • 4,584
  • 4
  • 26
  • 37