【问题标题】:Dart Unhandled Exception: Null check operator used on a null value, stack trace:Dart 未处理异常:对空值使用空检查运算符,堆栈跟踪:
【发布时间】:2021-09-09 07:55:09
【问题描述】:

虽然我已尝试应用我在 SO 上看到的大多数建议更改,但到目前为止没有任何效果。我在这里遇到了这个常见的异常 - roleRaw!.map((roleJson) => RoleModel.fromJson(roleJson)).toList();

这是代码

class RoleRepository {

  final RoleService roleService;
  RoleRepository({required this.roleService});

  Future<List<RoleModel>> fetchRoles() async {
      final roleRaw = await roleService.fetchRoles();
      final jSonConvert =  roleRaw!.map((roleJson) => RoleModel.fromJson(roleJson)).toList();
      return jSonConvert;
  }
}

错误信息

[ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: Null check operator used on a null value
E/flutter (20753): #0      RoleRepository.fetchRoles (package:etransfa/christdoes/bank/persistence/repository/role_repository.dart:11:35)
E/flutter (20753): <asynchronous suspension>

我能做什么?

【问题讨论】:

    标签: flutter flutter-state flutter-cubit


    【解决方案1】:

    你的方法roleService.fetchRoles()可以返回null吗?在这种情况下,问题是当您使用 null 检查运算符 (!) 时,它会在值为 null 时引发错误。

    在使用之前尝试验证响应:

    Future<List<RoleModel>> fetchRoles() async {
          final roleRaw = await roleService.fetchRoles();
          if (roleRaw != null) {
              final jSonConvert =  roleRaw!.map((roleJson) => 
              RoleModel.fromJson(roleJson)).toList();
              return jSonConvert;
          } else {
            // Handle null return here
          }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-19
      • 2021-07-22
      • 2021-08-19
      • 1970-01-01
      • 1970-01-01
      • 2017-05-08
      相关资源
      最近更新 更多