dartlambdalocal-variables

Why can't I declare this local variable in dart?


Why can't I declare a local variable inside a lambda function?

I have this code:

  @override
  Widget build(BuildContext context)
  {
    return new Expanded(
              child: new Listener(
                onPointerSignal: (event) => 
                {
                  double dist = 0.0; // Why does that not compile?
                  if (event is PointerScrollEvent)
                  {
                    dist = event.scrollDelta.dy,
                    onDrag(context, event.localPosition, dist.toInt(), true)
                  }
                },
                child: // .....
          ))
  };

I can declare the variable dist directly in the build method, then the code compiles. Has this something to do with the fact that apparently lambda methods can't contain statements, only expressions? It seems that using a ; to separate statements inside the lambda is also illegal. I can't seem to find the relevant specification, though.

I get three error messages on the line with double dist... : "Expected to find ','", "Undefined name 'dist'" and "Expected to find '}'".


Solution

  • In Dart, you can define a function with the shorthand syntax like this:

    ReturnType functionName() => expr;
    

    The => expr syntax is a shorthand for { return expr; }.

    Unlike in JavaScript, you can't put curly braces around the expression if you use the shorthand syntax. If you do it, the function will return a set, as {expr} is the syntax to define a set literal. This is what causes the error in your code.

    What you need is to use the function body syntax instead, which is done by the following:

    onPointerSignal: (event) {
      double dist = 0.0;
      if (event is PointerScrollEvent)
      // ...
    }
    

    The difference to your code is simply removal of the fat arrow syntax (=>).


    References: