简体   繁体   English

Flutter - 未处理的异常

[英]Flutter - Unhandled exception

I am learning flutter and I need so help / info regarding a weird behavior I'm experiencing.我正在学习 flutter,我需要有关我遇到的奇怪行为的帮助/信息。

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.当首选项为空时,它应该在 if 行触发未处理的异常。 Yet in debug on run the app is not crashing and the execution continues into the if statement.然而,在运行调试中,应用程序没有崩溃,并且继续执行到 if 语句。 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当我在调试控制台中进行评估时,确实会触发一个异常,但如果我没有检查的话我不会注意到它……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.如果没有数据preferences.getString(USER_TOKEN_PREFERENCE)将返回null并且您检查条件中的空字符串。 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 This article有一个很好的SharedPreferences示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM