I'm registering a user but when I fill form I get error
Unhandled Exception: type 'Null' is not a subtype of type 'String'
Error I'm getting on this line
authRepo.saveUserToken(response.body["token"]);
Here is registration method from
auth_controller.dart
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']);
// responseModel = ResponseModel(true, response.body["token"]);
} else {
responseModel =
ResponseModel(success: false, enMessage: response.statusText);
// responseModel = ResponseModel(false, 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:
Without seeing your saveUserToken
is difficult to say, but it seems that response.body["token"]
is null
and since saveUserToken
will be something like saveUserToken(String token) { ... }
, Dart is raising a type error.
I suggest you to check if your token is null or not and then throwing manually if it is. Something like this:
Future < ResponseModel > registration(SignUpBody signUpBody) async {
_isLoading = true;
update();
try {
Response response = await authRepo.registration(signUpBody);
late ResponseModel responseModel;
final String token = response.body["token"];
if (response.statusCode == 200 && token != null) {
authRepo.saveUserToken();
responseModel = ResponseModel(success: true, enMessage: response.body['token']);
} else {
throw new Error('A custom message');
}
} on Error catch (e) {
print(e);
responseModel = ResponseModel(success: false, enMessage: response.statusText);
} finally {
_isLoading = false;
update();
}
return responseModel;
}
CodePudding user response:
Check if response.body["token"]
is really not null. You can output the variable via console. Otherwise send the whole error message. It is certainly not only one single line long.
CodePudding user response:
if(response.body["token"]) // do things
wouldn't this work?