dart - 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;
解决方案
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.
推荐阅读
- powerbi - 如何将 sql 查询转换为 dax 查询
- python - 为多个文件 Python 运行相同的代码
- html - Bootstrap 导航栏徽标覆盖
- swiftui - onTapGesture 和 onLongPressGesture 没有响应
- python - 在python的条形图中将名称放在条形图中
- javascript - 从Angular中的异步函数解析数据时的空白图表
- c++ - 在这种情况下,C++ 标准是否保证模板实例化点?
- javascript - Nginx 音频文件 (wav/ogg/mp3) 不工作
- c# - C#如何检查代理服务器是否工作?
- javascript - VueJS中对象的过滤值