Flutter/Dart: 参数类型 'bool Function(MyStateNotifier)' 无法赋值给参数类型 'dynamic Function(dynamic)'

Flutter/Dart: The argument type 'bool Function(MyStateNotifier)' can't be assigned to the parameter type 'dynamic Function(dynamic)'

我在Dart中有一个这样的class声明,但是使用它时编译器报错

typedef ContextConditionFilter<T, bool> = bool Function(T);

class ContextStateWidget<T extends StateNotifier> extends StatefulWidget
{
    final Widget child;
    final ContextConditionFilter<T, bool> filter;
    const ContextStateWidget({Key key, @required this.child, @required this.filter}) : super(key: key);
}

一个class继承StateNotifier

class MyStateNotifier extends StateNotifier<DrawMenuState>
{
...
bool get myValue => return true;
}

正在使用

ContextStateWidget<MyStateNotifier>(
    filter: ((MyStateNotifier notifier) => notifier.myValue), // error here
    child: const OtherWidget()
);

错误

The argument type 'bool Function(MyStateNotifier)' can't be assigned to the parameter type 'dynamic Function(dynamic)'

您的代码有 2 个主要问题:

  1. 您应该为函数的输入命名,例如 notifier.
typedef ContextConditionFilter<T, V> = V Function(T notifier);
  1. 定义函数时使用=>时不需要return:
class MyStateNotifier extends StateNotifier<DrawMenuState> {
   bool get myValue => true;
}

如果您解决了这些问题,其他一切应该都能正常工作。

您的通知函数也不需要括号。

ContextStateWidget<MyStateNotifier>(
    filter: (MyStateNotifier notifier) => notifier.myValue,
    child: const OtherWidget(),
);

感谢aligator的回复,其实是分析器的问题。重启后 VSCode,问题消失了:-)