Home > Back-end >  Unhandled Exception: type 'Null' is not a subtype of type 'String' flutter
Unhandled Exception: type 'Null' is not a subtype of type 'String' flutter

Time:07-04

In postman when I registered user it can be but in app it can't. I've debug it and I found token is null. Kindly check it what I'm missing.

Here is postman body

{ "name": "vc",
    "email": "[email protected]",
    "password": "123456",
    "phone": "123456"
   }

and postman response

{
"success": true,
"en_message": "",
"ar_message": "",
"data": {
    "user": {
        "first_name": "vc",
        "username": "",
        "email": "[email protected]",
        "type": 1,
        "role_id": 4,
        "verification_code": 1261,
        "verified": 0,
        "phone": "123456",
        "updated_at": "2022-07-03T09:14:28.000000Z",
        "created_at": "2022-07-03T09:14:28.000000Z",
        "id": 127,
        "balance": [
            {
                "AED": 0
            }
        ]
    }
},
"status": 200
}

The error I'm getting here authRepo.saveUserToken(response.body["token"]);

Future<ResponseModel> registration(SignUpBody signUpBody) async {
    _isLoading = true;
    update();
    Response response = await authRepo.registration(signUpBody);
    late ResponseModel responseModel;
    if (response.statusCode == 200) {
      authRepo.saveUserToken(response.body["token"]);
      responseModel =
          ResponseModel(success: true, enMessage: response.body['token']);
    } else {
      responseModel =
          ResponseModel(success: false, enMessage: response.statusText);
    }
    _isLoading = false;
    update();
    return responseModel;
  }

saveUserToken

 Future<bool> saveUserToken(String token) async {
    apiClient.token = token;
    apiClient.updateHeader(token);
    return await sharedPreferences.setString(AppConstants.TOKEN, token);
  }

CodePudding user response:

Can't see token in your response body, but nonetheless, you should check if it's null before assigning it to a non-nullable parameter.

 if (response.statusCode == 200) {
      final String? token = response.body["token"];
       if(token != null) {
      authRepo.saveUserToken(token);
      responseModel =
          ResponseModel(success: true, enMessage: token
       } else {
      responseModel =
          ResponseModel(success: false, enMessage: response.statusText);
      }
    } else {
      responseModel =
          ResponseModel(success: false, enMessage: response.statusText);
    }
    _isLoading = false;
    update();
    return responseModel;
  }

Could be cleaner, to avoid repetition of code in the else part.

CodePudding user response:

For solving your error, you can write:

Future<bool> saveUserToken(String? token) async {
apiClient.token = token ?? '';
apiClient.updateHeader(token ?? '');
return await sharedPreferences.setString(AppConstants.TOKEN, token ?? '');
}
  • Related