I don´t understand the syntax of the then()
clause.
1. myFuture(6).then( (erg) => print(erg) )
What´s (erg) => expr
syntactically?
I thougt it could be a function, but
then( callHandler2(erg)
doesn´t work, Error:
"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. Is there a difference between the onError:
and the .catchError(e)
variants?
1) The Fat Arrow is syntactic sugar for short anonymous functions. The two functions below are the same:
someFuture(arg).then((erg) => print(erg));
// is the same as
someFuture(arg).then((erg) { return print(erg); });
Basically the fat arrow basically automatically returns the evaluation of the next expression.
If your callHandler2
has the correct signature, you can just pass the function name. The signature being that it accept the number of parameters as the future will pass to the then
clause, and returns null/void.
For instance the following will work:
void callHandler2(someArg) { ... }
// .. elsewhere in the code
someFuture(arg).then(callHandler);
2) See answer 1). The fat arrow is just syntactic sugar equivalent to:
myFuture(5).then( (erg){ callHandler(erg);}, onError: (e){ print(e); });
3) catchError
allows you to chain the error handling after a series of futures. First its important to understand that then
calls can be chained, so a then
call which returns a Future
can be chained to another then
call. The catchError
will catch errors both synchronous and asynchronous from all Future
s in the chain. Passing an onError
argument will only deal with an error in the Future
its an argument for and for any synchronous code in your then
block. Any asynchronous code in your then
block will remain uncaught.
Recent tendency in most Dart code is to use catchError
and omit the onError
argument.