Dart: Use generic extension method, get NoSuchMethodError: Class 'xxx' has no instance method 'yyy'

Dart extensions are static. They are syntactic sugar that is applied on types that are known at compilation time. This means that extensions will not work on dynamic values where the type is determined at runtime.

Your long, chained expression ends up using dynamic types probably where you aren't expecting it. One problem is that when you do .fold(0, (acc, i) => acc + i), the parameter and return types of the callback are not deduced. (See https://github.com/dart-lang/language/issues/731.) acc and the return type are thus assumed to be of type dynamic.

You can fix that by explicitly specifying a type for fold: .fold<double>(...).


In your edited version of your code, you introduced a second problem:

extension KtStd<T, R> on T {
  R let(R f(T it)) => f(this);
}

You intend for KtStd<T, R> to depend on let to constrain R, but that's backwards. let is not a legal call without first making KtStd<T, R> an extension on T. R therefore is unconstrained and is assumed to be dynamic. That then forces let to return dynamic too.

If possible, I suggest reverting to your earlier version where let is separately generic on R:

extension KtStd<T> on T {
  R let<R>(R f(T it)) => f(this);
}

You can more easily identify such errors during analysis by modifying your analysis_options.yaml file and setting:

analyzer:
  strong-mode:
    implicit-casts: false
    implicit-dynamic: false
  language:
    strict-raw-types: true

Tags:

Dart