7

I am new to flutter. I was using the camera plugin to add the camera to my app. And I got this warning Use a function declaration to bind a function to a name. How can I solve this one?

Code -

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

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

      onNewCameraSelected(description);
    };
Maahdi.Codes
  • 99
  • 2
  • 8
  • 1
    I believe the warning comes from this line `final onChanged = (CameraDescription? description) {`, which should be `onChanged(CameraDescription? description) {`, here is the specific rule https://dart-lang.github.io/linter/lints/prefer_function_declarations_over_variables.html – h8moss Nov 03 '21 at 13:21

1 Answers1

12

Dart's effective usage documentation suggests it is a better practice to use function declaration construct than it is to use assignment to an anonymous function.

That is

int foo() =>  1

instead of

int Function() foo = () => 1

In your example, that would mean declaring a function onChanged, instead of performing an assignment to onChanged:

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

The reason you're seeing this warning is that since Flutter 2.3.0 flutter_lints is by default packaged along with any flutter applications.

For more on Dart lints and effective usage, see the documentation on Effective Dart: Usage and List of Dart lints. Specifically, the warning you see is found on prefer_function_declarations_over_variables