You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter报错:Object类未定义getMessage方法,求原因及解决办法

问题描述

运行Flutter应用时出现如下错误:

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'.

已在自定义的APIConnexionException类中定义了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'),
                                      // 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}';
    }
}

请问该报错的原因是什么?是否需要修改getMessage方法的定义方式?


问题原因及解决方案

报错原因

Dart的catch (e)语句中,变量e的默认类型是Object,而Object类并没有定义getMessage()方法,所以直接调用e.getMessage()会触发这个错误。哪怕你抛出的是自定义异常,Dart也不会自动推断e的类型为你的自定义异常类。

解决方案

有两种可行的解决方式:

1. 指定异常类型捕获

你可以在catch块中判断异常类型,或者使用分类型捕获:

  • 方式一:类型判断
catch (e) {
    if (e is APIConnexionException) {
        print('caught api error: ${e.getMessage()}');
    } else {
        // 处理其他类型的异常
        print('caught other error: $e');
    }
}
  • 方式二:分类型捕获
on APIConnexionException catch (e) {
    print('caught api error: ${e.getMessage()}');
} catch (e) {
    // 处理其他异常
    print('caught other error: $e');
}

2. 重写toString()方法(推荐)

Dart中所有异常类通常都会重写toString()方法来提供友好的错误信息,这样不用额外定义getMessage(),直接打印e即可:
修改APIConnexionException类:

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

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

    @override
    String toString() {
        return 'code: $_statusCode message: $_message';
    }
}

然后在catch块中直接打印:

catch (e) {
    print('caught api error: $e');
}

是否需要修改getMessage方法?

不需要修改getMessage的定义方式,核心问题是捕获异常时没有明确类型导致Dart把e当成Object。当然如果选择第二种方案,你可以直接移除getMessage()方法,用toString()替代,这更符合Dart的编码习惯。


内容的提问来源于stack exchange,提问作者Duddy67

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 11:22:40