【问题标题】:Use a function declaration to bind a function to a name使用函数声明将函数绑定到名称
【发布时间】:2021-12-17 19:08:33
【问题描述】:

我是新来的颤振。我正在使用相机插件将相机添加到我的应用程序中。我收到了这个警告 Use a function declaration to bind a function to a name。我该如何解决这个问题?

代码-

Widget _cameraTogglesRowWidget() {
    final List<Widget> toggles = <Widget>[];

    final onChanged = (CameraDescription? description) {
      if (description == null) {
        return;
      }

      onNewCameraSelected(description);
    };

【问题讨论】:

  • 我相信警告来自final onChanged = (CameraDescription? description) {这行,应该是onChanged(CameraDescription? description) {,这里是具体规则dart-lang.github.io/linter/lints/…

标签: flutter flutter-widget flutter-plugin flutter-ios flutter-android


【解决方案1】:

Dart 的有效使用文档表明,使用函数声明构造比使用匿名函数赋值更好。

那是

int foo() =>  1

而不是

int Function() foo = () => 1

在您的示例中,这意味着声明一个函数 onChanged,而不是执行对 onChanged 的​​赋值:

void onChanged(CameraDescription? description){
  ...body
}

您看到此警告的原因是 since Flutter 2.3.0flutter_lints 默认与任何 Flutter 应用程序一起打包。

有关 Dart lints 和有效使用的更多信息,请参阅 Effective Dart: UsageList of Dart lints 上的文档。具体来说,您看到的警告位于prefer_function_declarations_over_variables

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多