DART: future 的语法 then

标签 dart dart-async

我不明白 then() 的语法条款。

1. myFuture(6).then( (erg) => print(erg) )
什么(erg) => expr语法上?

我认为它可能是一个函数,但是

then( callHandler2(erg)

不起作用,错误:
"Multiple markers at this line
- The argument type 'void' cannot be assigned to the parameter type '(String) -> 
 dynamic'
- Undefined name 'erg'
- Expected to find ')'"

2. myFuture(5).then( (erg) { callHandler(erg);}, onError: (e) => print (e)
What´s `onError: (e) => expr"` syntactically?

3. onError: 之间有区别吗?和 .catchError(e)变种?

最佳答案

1) Fat Arrow 是短匿名函数的语法糖。下面两个函数是一样的:

someFuture(arg).then((erg) => print(erg));
// is the same as
someFuture(arg).then((erg) { return print(erg); });

基本上,胖箭头基本上会自动返回下一个表达式的评估。

如果您的 callHandler2具有正确的签名,您只需传递函数名称即可。签名是它接受参数的数量,因为 future 将传递给 then子句,并返回 null/void。

例如以下将起作用:

void callHandler2(someArg) { ... }
// .. elsewhere in the code
someFuture(arg).then(callHandler);

2) 见答案 1)。胖箭头只是语法糖,相当于:

myFuture(5).then( (erg){ callHandler(erg);}, onError: (e){ print(e); });

3) catchError允许您在一系列 future 之后链接错误处理。首先重要的是要了解 then调用可以链接,所以 then返回 Future 的调用可以链接到另一个 then称呼。 catchError将捕获来自所有 Future 的同步和异步错误s 在链中。通过 onError参数只会处理 Future 中的错误。它是您的then 中任何同步代码的参数。堵塞。 then 中的任何异步代码块将保持未被捕获。

最近大多数 Dart 代码的趋势是使用 catchError并省略 onError争论。

关于DART: future 的语法 then,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20860863/

相关文章:

flutter - 跨多个窗口小部件传递Firebase用户Flutter

math - 如何使用Dart计算此数学?

image-processing - 如何在 iOS 的 flutter 中将图像流缓冲区转换为 jpeg 图像字节?

flutter - 使用 Provider 和模型类搜索/过滤 ListView

android - flutter : How to prevent rebuild of whole Reorderable Listview?

flutter - 如何在Dart中嵌套流(将流映射到流事件)?

dart - 为什么不设置var(Dart)

dart - 使用completeError 传递抛出的错误

selenium-webdriver - 在要检查的属性异步的流中查找元素

dart - 有没有办法取消 Dart future ?