【问题标题】:flutter: NoSuchMethodError: The getter 'isEmpty' was called on null颤振:NoSuchMethodError:在 null 上调用了 getter 'isEmpty'
【发布时间】:2018-12-14 10:23:24
【问题描述】:

我正在调用 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);
}

【问题讨论】:

  • 那是因为profile.message 返回null。你可能想要if(profile?.message?.isEmpty ?? true)
  • 感谢它为我工作。

标签: flutter dart is-empty


【解决方案1】:

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

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

? 防止错误如果表达式的前一部分导致 null?? true 导致 true 如果表达式的前一部分是 null 并因此处理 == null 和 @987654330 @if(...) 检查也是如此。

【讨论】:

    【解决方案2】:

    判断数组为空的时候,用什么来判断呢? Dart提供了isNotEmpty,但是在使用中经常会报错,因为你当时的数组可能不是[]和null。使用全文本时多加一层判断

    如果您的需求只是空或 null,您可以使用 Dart 的安全导航运算符使其更简洁:

    作为 isEmpty 函数,如果参数为 null 或空字符串,则返回 true

    if (routeinfo["my_value"]?.isEmpty ?? true) {
      // 
    }
    

    另一种写法:

    if ((value ?? '') == '') { ... }
    

    也这样做

     return (list == null || list .isEmpty) ? Container() : Container(child:Text('The current array is not empty'));
    

    【讨论】:

      猜你喜欢
      • 2020-06-28
      • 1970-01-01
      • 2021-06-03
      • 2021-05-29
      • 2020-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-18
      相关资源
      最近更新 更多