【发布时间】:2020-06-19 21:07:45
【问题描述】:
有什么区别:
未来
Future<void> copyToClipboard(BuildContext context, String text) async {
await Clipboard.setData(ClipboardData(text: text))
.then((_) => showSnackBar(context, 'Copied to clipboard'))
.catchError((Object error) => showSnackBar(context, 'Error $error'));
}
void、async、await、then、catchError
void copyToClipboard(BuildContext context, String text) async {
await Clipboard.setData(ClipboardData(text: text))
.then((_) => showSnackBar(context, 'Copied to clipboard'))
.catchError((Object error) => showSnackBar(context, 'Error $error'));
}
void,然后,catchError
void copyToClipboard(BuildContext context, String text) {
Clipboard.setData(ClipboardData(text: text))
.then((_) => showSnackBar(context, 'Copied to clipboard'))
.catchError((Object error) => showSnackBar(context, 'Error $error'));
}
所有方法都有效。如果我使用then 和catchError,我还需要将代码包装在async 函数中吗?
推荐的方式是什么?
【问题讨论】:
-
只有在函数体中使用
await时才使用async- 在这种情况下,async函数不应返回void,因为无法检查函数何时完成- 你应该返回一个Future(即使它是Future<void>) -
当使用
async/await东西时,有一点需要使用 Future` API -then()和catchError()- 更多阅读 dart.dev/codelabs/async-await 和 dart.dev/guides/libraries/futures-error-handling跨度>
标签: asynchronous flutter dart async-await