我不明白 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/