如何解决“类型‘Object’未定义getter‘message’”错误?
解决:The getter 'message' isn't defined for the type 'Object'
错误提示
The getter 'message' isn't defined for the type 'Object'. Try importing the library that defines 'message', correcting the name to the name of an existing getter, or defining a getter or field named 'message'.
问题截图

解决方案
类型强制转换:
Object类型本身没有message属性,捕获异常后可将其转换为具体异常类型(如Exception)再访问属性:try { // 执行可能抛出异常的代码 } catch (e) { print((e as Exception).message); }指定捕获的异常类型:在
catch时直接指定具体异常类型,避免接收为Object:try { // 执行可能抛出异常的代码 } on Exception catch (e) { print(e.message); }校验自定义异常类:如果使用自定义异常,需确保类中已定义
message属性,且捕获时匹配正确类型:class CustomException { final String message; CustomException(this.message); } try { throw CustomException("自定义异常信息"); } on CustomException catch (e) { print(e.message); }安全类型判断:不确定异常类型时,先做类型检查再访问属性,避免转换报错:
try { // 执行可能抛出异常的代码 } catch (e) { if (e is Exception) { print(e.message); } else { print(e.toString()); } }
内容的提问来源于stack exchange,提问作者Ahmed Yasser
相关产品推荐
相关产品推荐

