I'm a new flutter user here, so this time I have a problem when I login with API SERVICE, the login says
_CastError (Null check operator used on a null value)
the error is in the use of the source as below
Future<void> login(BuildContext context) async {
AppFocus.unfocus(context);
if (loginFormKey.currentState!.validate()) {
final LoginResponse? res = await apiRepository.login(
LoginRequest(
email: loginEmailController.text,
password: loginPasswordController.text,
),
);
final SharedPreferences prefs = Get.find<SharedPreferences>();
if (res!.accessToken.isNotEmpty) {
prefs.setString(StorageConstants.token, res.accessToken);
Get.toNamed(Routes.HOME);
Get.snackbar("Berhasil", "Selamat Berhasil Login");
} else {
Get.snackbar("title", "coab");
}
}
}
exactly the error appears in this section
if (res!.accessToken.isNotEmpty)
CodePudding user response:
final LoginResponse? res
you declare with ?
which means res
is nullable value.
but if (res!.accessToken.isNotEmpty)
you use !
which means, res is non-null
value. thats throw error
try to remove the !
mark.
if (res?.accessToken.isNotEmpty) {
... rest of your code
or add new contidion
if( res != null) {
if (res!.accessToken.isNotEmpty){
... rest of your code
}
}
hope it solve your issue. feel free to comment if any error occurred
CodePudding user response:
Try this code and test it.
Future<void> login(BuildContext context) async {
if (loginFormKey.currentState?.validate() ?? false) {
/*
your API code
*/
if (res.accessToken?.isNotEmpty ?? false) {
/*
if accessToken found
*/
} else {
/*
if accessToken not found
*/
}
}
return Future.value();
}