【问题标题】:How can i Convert this simple async,await formatted code using Future and .then() in dart (Flutter)?如何在 dart (Flutter) 中使用 Future 和 .then() 转换这个简单的 async,await 格式化代码?
【发布时间】:2020-03-25 10:47:38
【问题描述】:

在我说的sn-p代码下面:

void getlocation() async {
    Position position = await Geolocator()
    .getCurrentPosition(desiredAccuracy: LocationAccuracy.low);
    print(position);
}

我需要用 Dart (Flutter) 中的 Future 来编写这个函数。

提前致谢。

【问题讨论】:

  • Geolocator() .getCurrentPosition(desiredAccuracy: LocationAccuracy.low).then(print);
  • 但实际上async / await 有什么问题?为什么需要用Future.then()转换这么简单的例子?
  • 我正在学习他们两个。我正在试验并试图将一种转换为另一种。
  • 啊哈,祝你学习顺利 ;-)
  • 谢谢老兄。有很多东西要学:-)

标签: asynchronous flutter dart async-await


【解决方案1】:

future, then 方法的版本。

Future - 用于表示将来某个时间可用的潜在值或错误。

Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.best)
  .then((Position position) {
    print('Latitude : ${position.latitude}');
    print('Longitude : ${position.longitude}');
  }).catchError((err) {
    print(err);
  });

注意:如果您希望程序等到异步函数完成,请使用await,否则使用then

【讨论】:

    猜你喜欢
    • 2020-06-19
    • 2021-05-26
    • 2022-01-19
    • 2021-04-10
    • 2019-12-14
    • 1970-01-01
    • 2019-04-14
    • 1970-01-01
    • 2018-11-24
    相关资源
    最近更新 更多