当我从SharedPreferences中获取数据时,它不会在字符串中显示它,并且在此行中显示错误accountName:Text(sharedPreferenceEmail)
,
错误显示sharedPreferenceEmail = null
SharedPreferences sharedPreferences;
String sharedPreferenceEmail;
String value;
@override
void initState() {
super.initState();
getDataPreference();
}
getDataPreference() async {
sharedPreferences = await SharedPreferences.getInstance();
setState(() {
value = sharedPreferences.getString("email");
if(value != null) {
sharedPreferenceEmail = sharedPreferences.getString("email");
} else {
sharedPreferenceEmail = "Sign in with Google";
}
});
}
UserAccountsDrawerHeader(
decoration: BoxDecoration(color: Colors.blueGrey[900]),
accountName: Text(
sharedPreferenceEmail
),
enter image description here
最佳答案
如果您使用异步执行获取值,则需要防止null
在Flutter构建时(结果尚未到达)不会引起异常:
accountName: sharedPreferenceEmail != null ? Text( sharedPreferenceEmail ) : Container(),