Max
Max

Reputation: 1301

Problem with data sharedpreferences - Flutter

When I take the data from SharedPreferences, it does not show it in the string and gives an error in this line accountName: Text(sharedPreferenceEmail), in error shows that 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

Upvotes: 1

Views: 2559

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657018

If you acquire a value using async execution, you need to guard agains null to not cause an exception when Flutter builds while the result hasn't arrived yet:

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

Upvotes: 3

Related Questions