此异步方法会返回 True 还是 False?

问题描述 投票:0回答:1

我正在尝试检查 _isLoggedIn 变量是否已设置为 True、False 或 Empty。布尔变量将在用户登录后设置。假设用户尚未登录并且尚未设置或存储 isLoggedIn 记录。下面这个方法的返回值是多少?

  Future<bool> userIsLoggedIn() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    bool _isLoggedIn = prefs.getBool('isLoggedIn') as bool;
    return _isLoggedIn;
  }
flutter dart
1个回答
0
投票

如果你看一下

getBool
的实现。你会看到:

bool? getBool(String key) => _preferenceCache[key] as bool?;

这意味着,如果

isLoggedIn
中没有设置
SharedPreferences
键,那么
prefs.getBool('isLoggedIn')
将返回
null

现在,由于

_isLoggedIn
被声明为
bool
,因此将
null
(当该值不存在时)转换为
bool
as bool
会导致错误。

相反,我会选择:

Future<bool> userIsLoggedIn() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  bool? _isLoggedIn = prefs.getBool('isLoggedIn');
  return _isLoggedIn ?? false;
}

空感知运算符 (

??
) 用于在
_isLoggedIn
为空时提供默认值 (false)。

© www.soinside.com 2019 - 2024. All rights reserved.