简体   繁体   English

如何使用 flutter 的 .then() 方法捕获错误?

[英]How do I catch errors using flutter's .then() method?

I am using the Fluttery geolocator plugin to convert cooredinates into an address when a user searches for them.当用户搜索它们时,我正在使用 Fluttery geolocator 插件将坐标转换为地址。 However, when invalid coordinates are used, an exception is thrown but this is not handled as expected (code below).但是,当使用无效坐标时,会抛出异常,但这不会按预期处理(下面的代码)。

void placemarkFromCoordinates(latitude, longitude) async {
    Widget address;
    Geolocator().placemarkFromCoordinates(latitude, longitude).then((result) {
        print("result $result");
    }).catchError((error, stacktrace) {
        print(error);
    });

When an error is thrown, the error should be printed.当抛出错误时,应该打印错误。 However, the catch block is never reached and I am left with this exception:但是,永远不会到达 catch 块,我留下了这个异常:

Exception has occurred.发生异常。 PlatformException (PlatformException(ERROR_GEOCODING_INVALID_COORDINATES, Unable to find an address for the supplied coordinates.) PlatformException(平台异常(ERROR_GEOCODING_INVALID_COORDINATES,无法找到所提供坐标的地址。)

This error should be caught, but is not!这个错误应该被捕获,但不是!

Geolocator flutter 插件有一个 catchError 方法,所以用它代替 then

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM