首页 > 解决方案 > 颤振:NoSuchMethodError:在 null 上调用了 getter 'isEmpty'

问题描述

我正在调用 Web API 并接收 Profile 模型作为响应。当我使用下面的代码时,它会抛出一个错误:

try{
   if(profile.message.isEmpty){
      Navigator.of(context).pushNamed("/home");
   }else if(profile == null){
      _showDialog("Please check your internet connection");
   }else{
      _showDialog("Please enter valid credentials");
   }
}catch(exception){
   print(exception);
}

标签: flutterdartis-empty

解决方案


那是因为profile.message返回null. 你可能想要

if(profile?.message?.isEmpty ?? true)

?如果表达式的前一部分导致错误,则防止错误,如果表达式的前一部分是,则导致错误,null因此对检查进行相同处理。?? truetruenull== nullisEmptyif(...)


推荐阅读