首页 > 解决方案 > Can we set multiple callbacks with cascade notation using the arrow syntax in Dart?

问题描述

Is it possible to use the Cascade notation for setting multiple callbacks with the arrow syntax?

This code here shows an error, as it tries to set callback2 on int, the result of sum() and not MyClass:

void main() {
  MyClass mc = MyClass()
    ..callback1 = () => sum()
    ..callback2 = () => sum() // error here
    ;
}

class MyClass {
  Function callback1;
  Function callback2;
}

int sum() => 2 + 2;

标签: dart

解决方案


What you're doing is ambiguous to the parser, hence the error. If you wrap the closures in parens, the error goes away:

void main() {
  MyClass mc = MyClass()
    ..callback1 = (() => sum())
    ..callback2 = (() => sum());
}

class MyClass {
  Function callback1;
  Function callback2;
}

int sum() => 2 + 2;

Personally, I'd recommend creating variables for those callbacks and using those to assign to callback1 and callback2. Depending on your use case, it might be even better to pass these callbacks as parameters to a constructor instead.


推荐阅读