Problem with data sharedpreferences - Flutter

2,408

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(),
Share:
2,408
Max
Author by

Max

Updated on December 09, 2022

Comments

  • Max
    Max over 1 year

    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

    • Günter Zöchbauer
      Günter Zöchbauer about 5 years
      What happens if you use accountName: sharedPreferenceEmail != null ? Text( sharedPreferenceEmail ) : Container(),?
    • Max
      Max about 5 years
      and what to put in Container() ?
    • Günter Zöchbauer
      Günter Zöchbauer about 5 years
      Nothing, it's just a placeholder until the data from shared preferences becomes available. It's async and arrives with some delay, until then display an empty Container().
    • Max
      Max about 5 years
      I can not write it in accountName it is underlined
    • Günter Zöchbauer
      Günter Zöchbauer about 5 years
      Sorry, don't know what that means.
    • Max
      Max about 5 years
      Sorry, I was wrong, everything helped, thank you so much!)))
  • Max
    Max about 5 years
    Thanks for the help)
  • Günter Zöchbauer
    Günter Zöchbauer about 5 years
    If it solves your problem don't forget to accept the answer clicking the checkmark on the left below the up/down-vote button.