数据共享首选项出现问题-Flutter

时间:2019-02-09 11:52:50

标签: android dart flutter sharedpreferences

当我从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

1 个答案:

答案 0 :(得分:1)

如果您使用异步执行获取值,则需要再次警告null,以便在Flutter构建时(结果尚未到达)不会引起异常:

accountName: sharedPreferenceEmail != null ? Text( sharedPreferenceEmail ) : Container(),