'Unhandled Exception: Null check operator used on a null value profile_view.dart:938:61)

Unhandled Exception:

Null check operator used on a null value E/flutter (31702): #0 _ProfileViewState.login (package:.../profile/profile_view.dart:938:61)

profile_view.dart:938:61

 login(PhoneAuthCredential credential, RunMutation mutationCall) async {
    final UserCredential cr =
        await FirebaseAuth.instance.signInWithCredential(credential);
    final String firebaseToken = await cr.user!.getIdToken();
    final args = LoginArguments(firebaseToken: firebaseToken).toJson();
    final netResult = await mutationCall(args).networkResult;
    ***final loginRes = Login$Mutation.fromJson(netResult!.data!);***
    final jwt = loginRes.login.jwtToken;
    Hive.box('user').put('jwt', jwt);
    setState(() {
      verifyState = StepState.complete;
      _currentStep = 2;
    });
  }

how can I solve it ?



Solution 1:[1]

I will encourage not to use ! directly without checking null. In this snippet there are few cases we can get null.

Before using ! do a null check on the variable. like

final randomValue = .....;
if(randomValue !=null){ 
   usingAfterCheckingNull  = randomValue!.varriable
}

In your case, snippet can be like

login(PhoneAuthCredential credential, RunMutation mutationCall) async {
    final UserCredential cr =
        await FirebaseAuth.instance.signInWithCredential(credential);
    if (cr.user == null) {
      debugPrint("go null user");
      return;
    }
    final String firebaseToken = await cr.user!.getIdToken();
    final args = LoginArguments(firebaseToken: firebaseToken).toJson();
    final netResult = await mutationCall(args).networkResult;

    if (netResult != null && netResult!.data != null) {
      final loginRes = Login$Mutation.fromJson(netResult!.data!);
      final jwt = loginRes.login.jwtToken;
      Hive.box('user').put('jwt', jwt);
      setState(() {
        verifyState = StepState.complete;
        _currentStep = 2;
      });
    } else {
      debugPrint("others error");
    }
  }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yeasin Sheikh