Flutter错误: 类’Object’未定义方法’getMessage’。

huangapple go评论107阅读模式
英文:

Flutter error: The method 'getMessage' isn't defined for the class 'Object'

问题

这是您的代码的一部分,其中存在一个错误。错误信息是“方法 'getMessage' 未定义于 'Object' 类”,这是因为在异常类APIConnexionException中,您使用了late关键字来声明_message和_statusCode,这导致了类型问题。

要解决这个问题,您可以将late关键字从_message和_statusCode的声明中移除,并将其初始化为默认值。这将使编译器能够正确识别这些变量的类型。

以下是修复后的APIConnexionException类:

class APIConnexionException implements Exception {
  String _message;
  String _statusCode;

  APIConnexionException([String statusCode = '', String message = 'API Exception!']) {
    this._message = message;
    this._statusCode = statusCode;
  }

  String getMessage() {
    return 'code: ${this._statusCode} message: ${this._message}';
  }
}

这样,您应该能够消除“方法 'getMessage' 未定义于 'Object' 类”错误。

英文:
class WorldTime {

  String _url = 'https://api.api-ninjas.com/v1/worldtime?city';
  String location = 'London';
  String time = '';

  WorldTime({ required this.location });

  Future<void> getTime() async {

    try {
        final response = await get(Uri.parse('$_url=$location'),
                                      // Send authorization headers to the backend.
                                      headers: {'X-Api-Key': 'xxxxxxxxxxxxxxxxxxxxxxxxxx'},
        );

        Map data = jsonDecode(response.body);

        if (response.statusCode == 200) {
            time = "${data['hour']}:${data['minute']}";
        }
        else {
            throw new APIConnexionException(data['statusCode'], data['message']);
        }
    }
    catch (e) {
        print('caught api error: ${e.getMessage()}');
    }
  }
}



class APIConnexionException implements Exception {
    late String _message;
    late String _statusCode;

    APIConnexionException([ String statusCode = '', String message = 'API Exception!' ]) {
        this._message = message;
        this._statusCode = statusCode;
    }


    String getMessage() {
        return 'code: ${this._statusCode} message: ${this._message}';
    }
}

This is the error message I get when I run the app:

> The method 'getMessage' isn't defined for the class 'Object'.
> 'Object' is from 'dart:core'. Try correcting the name to the name of an existing method, or defining a method named 'getMessage'.

I don't understand this message. The getMessage() method is defined in my class.
Why am I getting this error ?
Should I define this method differently ?

答案1

得分: 1

我看到你正在抛出一个名为APIConnexionException的自定义异常,但你却捕获了通用的错误。这就是特定方法不可用的原因。

你应该捕获特定类型的异常,如下所示:

on APIConnexionException catch (e) {
    print('caught api error: ${e.getMessage()}');
}

你的更新后的代码段:

class WorldTime {

  String _url = 'https://api.api-ninjas.com/v1/worldtime?city';
  String location = 'London';
  String time = '';

  WorldTime({ required this.location });

  Future<void> getTime() async {

    try {
        final response = await get(Uri.parse('$_url=$location'),
                                      // 发送授权标头到后端.
                                      headers: {'X-Api-Key': 'xxxxxxxxxxxxxxxxxxxxxxxxxx'},
        );

        Map data = jsonDecode(response.body);

        if (response.statusCode == 200) {
            time = "${data['hour']}:${data['minute']}";
        }
        else {
            throw new APIConnexionException(data['statusCode'], data['message']);
        }
    }
    on APIConnexionException catch (e) {
        print('caught api error: ${e.getMessage()}');
    }
    
    catch (e) {
        print('caught api error: ${e.toString()}');
    }
  }
}



class APIConnexionException implements Exception {
    late String _message;
    late String _statusCode;

    APIConnexionException([ String statusCode = '', String message = 'API Exception!' ]) {
        this._message = message;
        this._statusCode = statusCode;
    }


    String getMessage() {
        return 'code: ${this._statusCode} message: ${this._message}';
    }
}
英文:

I can see that you are throwing a custom exception called APIConnexionException but you are catching general errors. That is why the particular method is not available.

You should catch the specific type of exception as

on APIConnexionException catch (e) {
    print(&#39;caught api error: ${e.getMessage()}&#39;);
}

Your updated code snippet:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-html -->

class WorldTime {

  String _url = &#39;https://api.api-ninjas.com/v1/worldtime?city&#39;;
  String location = &#39;London&#39;;
  String time = &#39;&#39;;

  WorldTime({ required this.location });

  Future&lt;void&gt; getTime() async {

    try {
        final response = await get(Uri.parse(&#39;$_url=$location&#39;),
                                      // Send authorization headers to the backend.
                                      headers: {&#39;X-Api-Key&#39;: &#39;xxxxxxxxxxxxxxxxxxxxxxxxxx&#39;},
        );

        Map data = jsonDecode(response.body);

        if (response.statusCode == 200) {
            time = &quot;${data[&#39;hour&#39;]}:${data[&#39;minute&#39;]}&quot;;
        }
        else {
            throw new APIConnexionException(data[&#39;statusCode&#39;], data[&#39;message&#39;]);
        }
    }
    on APIConnexionException catch (e) {
        print(&#39;caught api error: ${e.getMessage()}&#39;);
    }
    
    catch (e) {
        print(&#39;caught api error: ${e.toString()}&#39;);
    }
  }
}



class APIConnexionException implements Exception {
    late String _message;
    late String _statusCode;

    APIConnexionException([ String statusCode = &#39;&#39;, String message = &#39;API Exception!&#39; ]) {
        this._message = message;
        this._statusCode = statusCode;
    }


    String getMessage() {
        return &#39;code: ${this._statusCode} message: ${this._message}&#39;;
    }
}

<!-- end snippet -->

答案2

得分: 1

因为异常不知道异常的类型,所以出现了这个错误。为了解决这个问题,只需为异常 e 指定类型即可。

示例:

on APIConnexionException catch (e) {
      print('捕获到API错误: ${e.getMessage()}');
}
英文:

You are getting this error because exception doesn't know about the type of the exception. To solve this just give the type for the Exception e

Like:

on APIConnexionException catch (e) {
    print(&#39;caught api error: ${e.getMessage()}&#39;);
}

huangapple
  • 本文由 发表于 2023年3月8日 18:19:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/75671783.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定