简体   繁体   中英

Dart Unhandled Exception: Null check operator used on a null value, stack trace:

Though I have tried applying most of the suggested changes I have seen on SO, nothing has worked so far. I'm getting this common exception here - roleRaw!.map((roleJson) => RoleModel.fromJson(roleJson)).toList();

This is the code

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 message

[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>

What can I do?

Your method roleService.fetchRoles() can return null? in this case the problem is that when you use the null check operator (!) it throw an error when the value is null.

Try to validate the response before use it:

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
      }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM