我不明白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).fat arrow只是语法上的糖,相当于:

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

3)catchError允许您在一系列期货之后链接错误处理.首先,重要的是要了解then调用可以链接,因此返回Futurethen调用可以链接到另一个then调用.catchError将捕获来自链中所有Future的同步和异步错误.传递第onError个参数将只处理FutureITS中的错误,该参数用于和用于then挡路中的任何同步码.then挡路中的任何异步代码都将保持不被捕获.

大多数DART代码的最新趋势是使用catchError而省略onError参数.

Dart相关问答推荐

如何防止 Riverpod 的 ConsumerWidget 重建管理 ThemeMode

在Flutter中重命名文件/图像

如何在 Dart 中将代码迁移到 null 安全

是否从 Dart 中删除了interface关键字?

flutter pub run build_runner 卡住了

如何在streambuilder中查询firestore文档并更新listview

如何根据 Select 的选项卡更改样式?

在 Flutter 中将图像与左上角对齐

使用 Google Dart 进行数据库查询?

dart- 四舍五入

Flutter Drawer Widget - 更改 Scaffold.body 内容

如何从目录中获取文件列表并将其传递给ListView?

如何在dart中的多个文件中编写多个单元测试?

在 Dart 中使用固定长度列表有性能优势吗?

如何在 Dart 中将字符串转换为 utf8?

如何在dart中获得一周的开始或结束

是什么使它成为 Dart 中的固定长度列表?

从 Dart 调用 javascript

你如何在 Dart 中对异常进行单元测试?

Dart中var和dynamic类型的区别?