Recover value if null in Flutter Sharedpreferences

Asked

Viewed 116 times

-2

I’m learning to flutter these days.

I’m studying Shared Preferences:

When I save to Shared Preferences and retrieve the information, it works, but when I remove and try to retrieve the information, I’d like you to display the text "Worthless". But gives error in the app

Follows part of the code and its functions

  TextEditingController _controllerCampo = TextEditingController();
  String _textoSalvo = "Nada salvo!";

  _salvar() async{

    String valorDigitado = _controllerCampo.text;

    final prefs = await SharedPreferences.getInstance();
    await prefs.setString("nome", valorDigitado);
    print("operacao (salvar) $valorDigitado");
  }
  _recuperar() async {

    final prefs = await SharedPreferences.getInstance();
    setState(() {
      _textoSalvo = prefs.getString("nome") ?? "Sem valor";
    });

  }

  _remover() async{
      final prefs = await SharedPreferences.getInstance();
      prefs.remove("nome");
      setState(() {
        _textoSalvo = "";
      });
  }

Right here

_textoSalvo = prefs.getString("nome") ?? "Sem valor";

Here is the snippet to add the text and buttons

     TextField(
              keyboardType: TextInputType.text,
              decoration: InputDecoration(
                labelText: "Digite algo"
              ),
              controller: _controllerCampo,
            ),
            Row(
              children: <Widget>[
                RaisedButton(
                  color: Colors.blue,
                  textColor: Colors.white,
                  padding: EdgeInsets.all(15),
                  child: Text(
                    "Salvar",
                     style: TextStyle(
                       fontSize: 15
                     ),
                  ),
                  onPressed: _salvar,
                ),
                RaisedButton(
                  color: Colors.blue,
                  textColor: Colors.white,
                  padding: EdgeInsets.all(15),
                  child: Text(
                    "Recuperar",
                    style: TextStyle(
                      fontSize: 15
                    ),
                  ),
                  onPressed: _recuperar,
                ),
                RaisedButton(
                  color: Colors.blue,
                  textColor: Colors.white,
                  padding: EdgeInsets.all(15),
                  child: Text(
                    "Remover",
                    style: TextStyle(
                      fontSize: 15
                    ),
                  ),
                  onPressed: _remover,
                )

Makes that mistake

inserir a descrição da imagem aqui

Where can I be missing?

  • 1

    Please enter the complete code. Especially the part of Text you create with the _textoSalvo. The error is not in what you showed.

  • I added the other methods

2 answers

1

Test if there’s a key first:

_recuperar() async {

final prefs = await SharedPreferences.getInstance(); 
if (prefs.containsKey("nome"))
{
    setState(() 
    { 
       _textoSalvo = prefs.getString("nome"); 
    });
} 

}

1


The error is not in this method you are showing. Therefore, complete code is required for analysis.

Like _recuperar() is asynchronous, most likely the _textoSalvo is null when running build and render the screen, which causes the error. After all, the Future will be completed with the result only in the next Event loop of solate.

To test, change your Text for Text(_textoSalvo ?? 'teste') and the error must disappear.

  • I added the other methods to the question

  • Really. I stopped the app, restarted the pc, tested and worked

Browser other questions tagged

You are not signed in. Login or sign up in order to post.