【问题标题】:The method '[]' can't be unconditionally invoked because the receiver can be 'null'. Try making the call conditional (using '?.')方法 \'[]\' 不能无条件地调用,因为接收者可以是 \'null\'。尝试使调用有条件(使用 \'?.\')
【发布时间】:2022-11-17 10:03:49
【问题描述】:

我想在 flutter 上使用 horizo​​ntal_data_table 从 API 调用数据。这是出现错误的代码

       Container(
          width: 200,
          height: 52,
          padding: const EdgeInsets.fromLTRB(5, 0, 0, 0),
          alignment: Alignment.centerLeft,
          child: Text(widget.leavelistmodel.response[index].paidLeaveEmployeeNip),
        ),

结果的数据模型如下所示:

class LeaveListResult {
  int? paidLeaveId;
  String? paidLeaveEmployeeNip;
  String? paidLeaveEmployeeFullName;
}

我已经把它改成了?和 !它仍然有错误,我该如何修复错误?

【问题讨论】:

    标签: android ios flutter dart


    【解决方案1】:

    我们使用 nullSafty 作为模型变量。 ?

    class LeaveListResult {
      int? paidLeaveId;
      String? paidLeaveEmployeeNip;
      String? paidLeaveEmployeeFullName;
    }
    

    既然和Swift的optional一样,nullSafty就必须要取消。

    Container(
              width: 200,
              height: 52,
              padding: const EdgeInsets.fromLTRB(5, 0, 0, 0),
              alignment: Alignment.centerLeft,
              child: Text(widget.leavelistmodel.response[index].paidLeaveEmployeeNip ?? 'NULL'),
            ),
    

    您可以使用! 强制解包,但这不是一个好的做法。原因是当它为空时会出错。当使用channing为空时,应该显示异常处理消息而不是错误。

    【讨论】:

      【解决方案2】:

      Text 不能接受可为 null 的 String?,如果您确定您的数据不是 null,请执行以下操作:

        child: Text(widget.leavelistmodel!.response[index]!.paidLeaveEmployeeNip),
      

      您还可以为 String? 设置默认值,当它是 null 时将显示该默认值:

        child: Text(widget.leavelistmodel?.response[index]?.paidLeaveEmployeeNip ?? "default value"),
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-08-24
        • 2022-08-21
        • 2023-03-05
        • 1970-01-01
        • 2023-04-10
        • 2021-10-05
        • 1970-01-01
        • 2021-08-27
        相关资源
        最近更新 更多