简体   繁体   中英

Flutter - Unhandled exception

I am learning flutter and I need so help / info regarding a weird behavior I'm experiencing.

Future<SharedPreferences> _preferences = SharedPreferences.getInstance();
final SharedPreferences preferences = await _preferences;
if (preferences.getString(USER_TOKEN_PREFERENCE) != '') {
  yield AuthentificationStatus.passed;
}

When the preferences are empty it's supposed to fire an Unhandled exception at the if line. Yet in debug on run the app is not crashing and the execution continues into the if statement. When I evaluate in debug console an exception is indeed fired but if I wouldn't have noticed it if I hadn't checked...p

So why the execution is not stopping and the exception logged?

Thanks

execution is not stopping

because of your condition. if there is no data preferences.getString(USER_TOKEN_PREFERENCE) will return null and you check empty String in the condition. You should check

if (preferences.containsKey(USER_TOKEN_PREFERENCE) && preferences.getString(USER_TOKEN_PREFERENCE) != '') {
  yield AuthentificationStatus.passed;
}

or,

if (preferences.getString(USER_TOKEN_PREFERENCE) != null && preferences.getString(USER_TOKEN_PREFERENCE) != '') {
      yield AuthentificationStatus.passed;
    }

This article has a good example of SharedPreferences

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